Merge pull request #714: feat(git): a Fetch button in the Git status header, and an interval for it app-wide and per case

Conflict in CLAUDE.md (Adding Features, App setting) resolved by keeping
both sides: #714's sentence that a setting the server acts on must be
synced, after the `.strict()` clause, and #719's mutateSettingsFile() rule
at the end of the bullet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Codeman maintainer committed 2026-10-27 02:11:49 +01:00
commit 6612a89ebc
36 files changed
+3662 -44

No files matched your search

+4 -2
View File
@@ -236,7 +236,9 @@ The terminal provider scans `terminalLinkLine()`, which extends `terminalPathLin
**Files panel search** (COD-236, the `q` param on `GET /api/sessions/:id/files`): `compileFileQuery()` (`utils/file-query.ts`, pure) compiles the query into a predicate the server-side walk prunes with; a query returns a FLAT match list and the walk recurses past non-matching directories. An empty, whitespace-only or overlong (`MAX_QUERY_LENGTH`, 256) query compiles to `null`, keeping the default tree response byte-identical. ⚠️ **Never compile a glob into a RegExp** (`*a*a*a…` backtracks and freezes the event loop for the whole server): `globMatch()` is a two-pointer wildcard walk. → [architecture-invariants#files-panel-search](docs/architecture-invariants.md#files-panel-search)
**Git status indicator** (`showGitStatus`, per-device, default OFF; `src/git-workspace-status.ts`, `routes/git-status-routes.ts`, `git-status-ui.js`): the bottom-bar indicator and its panel read `GET /api/sessions/:id/git-status` and `/git-diff`, read-only and offline (it never fetches and never writes). ⚠️ git never runs on a repository at or inside a Docker case workspace (walk-up, scan and diff alike, and a cached repository list is re-checked against the CURRENT Docker roots), since a container could plant a clean filter that runs on the host; remote and Docker sessions answer `unsupported`. ⚠️ `git-diff` takes `repo`/`path`/`kind` only as keys matched against the workspace's own repository list (`findWorkspaceRepo()`) and that repository's current status, never as paths. ⚠️ Keep `--no-optional-locks`, `core.fsmonitor=false` and `log.showSignature=false` on every call and `--no-ext-diff --no-textconv` on diffs; clean filters still run, which is why the Docker rule exists. ⚠️ An enclosing repository at `$HOME` or above is ignored (`isUnrelatedAncestor()`), and is identified by one cached `rev-parse` before any full status runs. Everything git supplies renders via `textContent`. Tests: `test/git-workspace-status.test.ts`, `test/routes/git-status-routes.test.ts`, and `test/git-status.browser.test.ts` (browser suite, not in the gate).
**Git status indicator** (`showGitStatus`, per-device, default OFF; `src/git-workspace-status.ts`, `routes/git-status-routes.ts`, `git-status-ui.js`): the bottom-bar indicator and its panel read `GET /api/sessions/:id/git-status` and `/git-diff`, read-only and offline on its own (it never fetches; fetching is the separate path below). ⚠️ git never runs on a repository at or inside a Docker case workspace (walk-up, scan and diff alike, and a cached repository list is re-checked against the CURRENT Docker roots), since a container could plant a clean filter that runs on the host; remote and Docker sessions answer `unsupported`. ⚠️ `git-diff` takes `repo`/`path`/`kind` only as keys matched against the workspace's own repository list (`findWorkspaceRepo()`) and that repository's current status, never as paths. ⚠️ Keep `--no-optional-locks`, `core.fsmonitor=false` and `log.showSignature=false` on every call and `--no-ext-diff --no-textconv` on diffs; clean filters still run, which is why the Docker rule exists. ⚠️ An enclosing repository at `$HOME` or above is ignored (`isUnrelatedAncestor()`), and is identified by one cached `rev-parse` before any full status runs. Everything git supplies renders via `textContent`. Tests: `test/git-workspace-status.test.ts`, `test/routes/git-status-routes.test.ts`, and `test/git-status.browser.test.ts` (browser suite, not in the gate).
**Git fetch** (`src/git-fetch.ts`, `src/git-fetch-scheduler.ts`, `routes/git-status-routes.ts`, the panel's **Fetch** button): `POST /api/sessions/:id/git-fetch` is the ONLY git command the Git PANEL runs that WRITES — cloning and worktree management write too, but only when the user asked for them at that moment — and it is the only one that can run later by itself, on a timer, and the only one that can run a repository's own hooks (`reference-transaction`, `pre-auto-gc` through the automatic maintenance a fetch triggers, config commands such as `credential.helper`) — which is why it is opt-in and never runs on a timer until the user turns it on. ⚠️ Fetch updates remote-tracking refs only; it must never commit, check out, merge or touch the working tree. ⚠️ It is not as harmless as a read: a fetch holds git's ref lock, so an agent's own `git pull` in the same clone can hit the same `cannot lock ref` — hence one folder is fetched by at most one run at a time (`fetchWorkspaceOnce` joins a run already going), and `FETCH_CONFIG_ARGS` (`-c core.fsmonitor=false -c maintenance.auto=false -c gc.auto=0`) keeps an unattended fetch from starting a gc in a repository the agent is using. ⚠️ `buildFetchArgs()` is `['fetch', '--quiet']` and must stay verb-invariant (`test/git-fetch.test.ts`); those `-c` overrides are added by the runner, not by `buildFetchArgs()`. ⚠️ The git timeout must reach the whole process TREE, not just the `git` parent: `execFile` signals the parent only, so `runFetch` spawns `detached` and signals the negative pid (SIGTERM, then SIGKILL `FETCH_KILL_ESCALATION_MS` later), and the caller is answered AT the timeout while the group is still dying — that is the point. `test/git-fetch.test.ts` proves it against a local server that never answers, by group membership rather than parentage. A non-zero exit must still reject the way `execFile` would, or a real failure reads as a clean run with no reason. ⚠️ The same Docker rule as above applies BEFORE any git runs (a repository at or inside a Docker case workspace is refused), and remote sessions answer `unsupported`. ⚠️ Keep it non-interactive (`gitNonInteractiveEnv()`: `GIT_TERMINAL_PROMPT=0` + BatchMode ssh) or a fetch hangs on an invisible login prompt — but that BatchMode ssh is a DEFAULT, never an override: `fetchEnvFor` must not overwrite the repository's `core.sshCommand`, the user's own `GIT_SSH_COMMAND` or a `GIT_SSH` (`readRepoSshCommand` reads it inside the same limiter slot and the same wall-clock bound as the fetch it serves, and the spawn gets only what the read left), and `StrictHostKeyChecking=accept-new` writes an unknown host key into `~/.ssh/known_hosts` without asking — BatchMode stops a prompt, not a write. Keep it bounded: `MAX_REPOS`/`MAX_REPOS_LIMIT` (12/50), `MAX_FETCH_OUTPUT_BYTES` (2 MB), the git timeout per spawn, and `FETCH_CONCURRENCY` (4) as ONE `Limiter` shared by the fetches of the whole tick — `createLimiter` keeps its count in the closure, so a limiter that delegated to `mapLimited` per call bounds each call, and 4 folders × 4 repositories would start 16 git processes. ⚠️ One semaphore cannot bound both the folders and the fetches: a folder holding a slot would then wait for a slot its own fetch needs, so the tick bounds its folders with `mapLimited` and hands the shared bound to every run. ⚠️ Failure text reaching a client is control-stripped and credential-redacted (`sanitizeGitOutput`) and the browser writes it with `textContent`. Scheduler semantics: settings are read fresh each tick (`GIT_FETCH_TICK_INTERVAL_MS`, 15 s), a per-session override wins even while the app-wide switch is off, the interval is timed from the run START, state is keyed by FOLDER (sessions sharing one folder are the same clone, so one run serves them all, the schedule is stamped at selection, and every session on a folder is remembered, a folder is due when ANY session open on it is due — so the order the sessions were read cannot decide which interval wins (both orders are tested) — and the folder is probed once for the whole group rather than once per session on it — closing the one that holds the override must not stop the folder's fetching while another session is still open on it), a tick is skipped while the previous one is still going, and a user-chosen folder is probed BOUNDED with the default options before anything runs (rule #516 — `unknown` is never read as `absent`). ⚠️ The two settings (`gitFetchEnabled`, `gitFetchIntervalSeconds`, off/300 by default, clamped 30–3600) are **synced**, not per-device: they must stay out of `displayKeys` and out of the strip destructure in settings-ui.js, or the scheduler reads nobody's value. Per-session state rides `SessionUpdated` (no new SSE event) as `gitFetch`, and the click route publishes the run's trigger, not the request's: `trigger: 'click'` only when the click was the run, because a click that joined a tick already going fetcLine truncated
**Raw file bodies are streamed and range-aware**: `file-raw`, the attachments `/raw` route, `GET /api/download` and the rendered-HTML route `GET /html-view/<cap>/...` share `sendFileBody()`, advertise `Accept-Ranges: bytes` and answer `Range` with `206` + `Content-Range` (single-range, parser in `src/web/http-range.ts`); without it `<video>` cannot seek. The size cap (`MAX_FILE_DOWNLOAD_BYTES`, default 2GB, env `CODEMAN_MAX_DOWNLOAD_BYTES`, `0` = unlimited) is a sanity bound, not memory protection; never reintroduce a whole-file buffer. ⚠️ Bodies go out via `reply.hijack()`, so `sendRawStream` must copy the status onto `reply.raw` by hand or a partial body ships as `200`. ⚠️ Closing the preview must pause and unload media (`_stopFilePreviewMedia`), since a detached `HTMLMediaElement` keeps playing. → [architecture-invariants#raw-file-bodies-streamed-and-range-aware](docs/architecture-invariants.md#raw-file-bodies-streamed-and-range-aware)
@@ -304,7 +306,7 @@ One module per domain in `src/web/routes/` (plus a barrel; `ls src/web/routes/`
- **API endpoint**: Types in `src/types/` domain file, route in `src/web/routes/*-routes.ts`. Return the `ApiResponse` envelope (`{ success: true, data }`; errors via `createErrorResponse()` with proper status code). Validate with Zod schemas in `schemas.ts`.
- **SSE event**: Add to `src/web/sse-events.ts` + `SSE_EVENTS` in `constants.js`, emit via `broadcast()`, handle in `app.js` (`addListener(`)
- **Session setting**: Add to `SessionState`, include in `session.toState()`, call `persistSessionState()`
- **App setting**: decide per-device vs synced first. Per-device keys go in the `displayKeys` set in settings-ui.js and must NOT be added to `SettingsUpdateSchema` (it is `.strict()`). ⚠️ Anything in `PUT /api/settings` that acts on a setting (the `toggleService` watcher calls) must resolve from **`merged`** (persisted + incoming), never from the raw request body: a partial PUT omits keys it doesn't intend to change, and `body.x ?? default` turns every omission into "apply the default" and silently resets live services. Pinned by `test/routes/system-routes-settings-partial-put.test.ts`. ⚠️ A synced setting is admin-only to write in multi-user mode (the PUT 403s a non-admin, whose browser does not send it): a new route that writes `settings.json` takes the same `isMultiUserMode() && !requireAdmin(req, reply)` gate. ⚠️ Every write to the server's `settings.json` goes through `mutateSettingsFile()` (`src/web/settings-writer.ts`: one at a time, tmp+rename, and a file that does not parse is refused, never read as `{}`), and a route awaits it before answering: two unserialized plain `writeFile`s tore the file, and the `{}` fallback then erased every other setting. The one direct writer is config-backup restore (`restoreConfigBackup()`, as for `clis.json`): it must work on a file that does not parse, which the writer refuses. Pinned by `test/settings-json-write-serialization.test.ts`.
- **App setting**: decide per-device vs synced first. Per-device keys go in the `displayKeys` set in settings-ui.js and must NOT be added to `SettingsUpdateSchema` (it is `.strict()`). ⚠️ A setting the server ACTS on must be synced, never a display key and never stripped by `saveAppSettings`: a per-device value never reaches the server, so a scheduler or watcher reads nobody's number (the Git fetch rows are pinned by `test/app-settings-structure.test.ts`). ⚠️ Anything in `PUT /api/settings` that acts on a setting (the `toggleService` watcher calls) must resolve from **`merged`** (persisted + incoming), never from the raw request body: a partial PUT omits keys it doesn't intend to change, and `body.x ?? default` turns every omission into "apply the default" and silently resets live services. Pinned by `test/routes/system-routes-settings-partial-put.test.ts`. ⚠️ A synced setting is admin-only to write in multi-user mode (the PUT 403s a non-admin, whose browser does not send it): a new route that writes `settings.json` takes the same `isMultiUserMode() && !requireAdmin(req, reply)` gate. ⚠️ Every write to the server's `settings.json` goes through `mutateSettingsFile()` (`src/web/settings-writer.ts`: one at a time, tmp+rename, and a file that does not parse is refused, never read as `{}`), and a route awaits it before answering: two unserialized plain `writeFile`s tore the file, and the `{}` fallback then erased every other setting. The one direct writer is config-backup restore (`restoreConfigBackup()`, as for `clis.json`): it must work on a file that does not parse, which the writer refuses. Pinned by `test/settings-json-write-serialization.test.ts`.
- **Hook event**: Add to `HookEventType`, add hook in `hooks-config.ts:generateHooksConfig()`, update `HookEventSchema`
- **Mobile feature**: Add to relevant singleton, guard with `MobileDetection.isMobile()`. New header buttons must stay off phones (`test/mobile-header-buttons-policy.test.ts`).
- **New test**: a test that constructs `WebServer` itself binds port 0 (`new WebServer(0, …)`, then `server.boundPort`), and a raw `http`/`net`/Fastify/`ws` server listens on `0` and reads `address().port`; mobile tests get theirs from `createTestServer()` and read `boundPort` too. `test/test-ports-guard.test.ts` refuses a fixed port in either. Route tests use `app.inject()` (no port needed); see `test/routes/_route-test-utils.ts`.
+1 -1
View File
@@ -460,7 +460,7 @@ PTY Output → 16ms Server Batch → DEC 2026 Wrap → SSE → Client rAF → xt
- **Background daemon & service install** — `codeman web -d` runs the server detached with a pidfile, `~/.codeman/web.log`, and verified startup (it polls the server until it answers, so a port clash never reads as success); `codeman service install` writes a systemd user unit (Linux) or LaunchAgent (macOS) with your shell's PATH baked in, so an nvm or Homebrew `node`, `tmux` and `claude` are actually found. Secrets are never written into unit files
- **Diagnostics in Settings** — **App Settings → System → Diagnostics → Run checks** runs `codeman doctor` on the server and lists Node, tmux, every agent CLI and the optional office tools with versions, paths and install hints. Besides the `PATH`, it also looks in each CLI's usual install directories (`~/.local/bin`, `~/.npm-global/bin` and the like), so most installs are found under a service with a minimal `PATH`. Admin only in multi-user mode.
- **Self-update** — git-clone installs under systemd/launchd update in place from **App Settings → System → Updates**: it detects the latest release, auto-stashes a dirty tree, and streams build progress across the service restart (npm installs report as non-updatable)
- **Git status in the bottom bar** — off by default (**App Settings → Header & Panels → Bottom bar → Git status**, per device). A small indicator at the right of the bottom bar shows the active session's repository at a glance: `● 3` uncommitted files, `↑ 2` commits not pushed, `⚠` merge conflicts, `✓` all committed and pushed. Click it for a draggable window listing the staged, not-staged, untracked and conflicted files (grouped under collapsed folders, or as a flat list if you turn that setting off) and the unpushed commits; **click a file to see its diff** (new files as all additions, deleted files as all removals), with **Open file** to jump to the viewer. A folder that holds several projects gets one collapsible section per repository found up to two levels down, all collapsed until you open them. Read-only and offline (Codeman never fetches or changes the repo); not shown for Docker or remote sessions.
- **Git status in the bottom bar** — off by default (**App Settings → Header & Panels → Bottom bar → Git status**, per device). A small indicator at the right of the bottom bar shows the active session's repository at a glance: `● 3` uncommitted files, `↑ 2` commits not pushed, `⚠` merge conflicts, `✓` all committed and pushed. Click it for a draggable window listing the staged, not-staged, untracked and conflicted files (grouped under collapsed folders, or as a flat list if you turn that setting off) and the unpushed commits; **click a file to see its diff** (new files as all additions, deleted files as all removals), with **Open file** to jump to the viewer. A folder that holds several projects gets one collapsible section per repository found up to two levels down, all collapsed until you open them. **Fetch** in that window's header runs `git fetch` for the repositories it lists, on your click or on an interval you turn on (**App Settings → Bottom bar**, off by default; **Session Options → Git** overrides both the switch and the interval per session). Sessions open on the same folder share one run and each sees its result. Apart from that fetch Codeman never fetches or changes the repo, so "behind" is as of the last fetch; not shown for Docker or remote sessions.
- **Clone a GitHub repo as a case** — paste a repository URL into **Add Case → Clone Repo** and Codeman clones it into `~/codeman-cases/<name>` and registers it as a normal case, ready to run an agent in. It preflights the URL while you type (tells you whether it can be cloned anonymously and offers the repo's real branches and tags for the optional branch/tag field), fills the case name in from the URL, and lets you pick which CLI the Run button should use. Public repositories over `https://`; Codeman never collects or stores credentials
- **Create a case in a custom folder** — tick **Create in a custom folder** in **Add Case → Create New**, pick a parent folder (Browse included) and a name, and Codeman scaffolds the new case there instead of `~/codeman-cases`. The target must be a new or empty folder; system directories, your home folder itself, credential trees such as `~/.ssh`, and Codeman's own data folder are refused. Admin only in multi-user mode.
- **Multi-CLI** — run **Claude Code**, **OpenCode**, **Codex**, **Antigravity**, **Gemini**, **Pi**, **Grok**, **DeepSeek Harness**, **OMP**, or **GitHub Copilot CLI** per session; env-var prefixes auto-gate (`CLAUDE_CODE_*` vs `OPENCODE_*` vs `CODEX_*` vs `ANTIGRAVITY_*` vs `GEMINI_*`/`GOOGLE_*` vs `PI_*` vs `GROK_*`/`XAI_*` vs `DSH_*`/`DEEPSEEK_*` vs `OMP_*` vs `COPILOT_*`). See [`docs/opencode-integration.md`](docs/opencode-integration.md), [`docs/pi-integration.md`](docs/pi-integration.md), [`docs/grok-integration.md`](docs/grok-integration.md), [`docs/deepseek-integration.md`](docs/deepseek-integration.md) [`docs/omp-integration.md`](docs/omp-integration.md) and [`docs/copilot-integration.md`](docs/copilot-integration.md)
+7 -1
View File
@@ -1152,7 +1152,7 @@ Admin only in multi-user mode (`403`), like `POST /api/cases/link`: it writes ou
## Git status
`GET /api/sessions/:id/git-status` is what the bottom-bar Git indicator and its panel read (Settings → Header & Panels → Bottom bar, per-device, default off). It reports what the session's workspace has not committed or pushed. **Read-only and offline:** it never fetches, pulls, commits or writes (it runs `git status` with `--no-optional-locks`, so it does not even refresh the index), which is why `behind` is as of the last `git fetch`. The session is resolved like every session route (ownership via `findSessionOrFail`; another user's session is `404`). A repository whose root is, or is inside, a Docker case workspace is dropped (from the walk-up, the scan below a folder, and the diff route): a container can write there, and a repository's own clean filter or signature program would run on the host. When a branch's upstream does not exist on the remote (deleted and pruned, or never pushed, as after cloning an empty repository and committing), `upstreamGone` is `true` and the unpushed list falls back to commits on no remote-tracking ref at all.
`GET /api/sessions/:id/git-status` is what the bottom-bar Git indicator and its panel read (Settings → Header & Panels → Bottom bar, per-device, default off). It reports what the session's workspace has not committed or pushed. **Read-only and offline:** it never fetches, pulls, commits or writes (it runs `git status` with `--no-optional-locks`, so it does not even refresh the index), which is why `behind` is as of the last `git fetch` — the panel's Fetch button is a separate route, below. The session is resolved like every session route (ownership via `findSessionOrFail`; another user's session is `404`). A repository whose root is, or is inside, a Docker case workspace is dropped (from the walk-up, the scan below a folder, and the diff route): a container can write there, and a repository's own clean filter or signature program would run on the host. When a branch's upstream does not exist on the remote (deleted and pruned, or never pushed, as after cloning an empty repository and committing), `upstreamGone` is `true` and the unpushed list falls back to commits on no remote-tracking ref at all.
`GET /api/sessions/:id/git-diff?repo=<repoRoot>&path=<path>&kind=staged|unstaged|untracked|conflicted` returns the unified diff of one file the panel lists (`{ diff, truncated, binary }`; staged is index vs HEAD, unstaged is working tree vs index, untracked is the whole file as additions). It is what opens when you click a file in the Git panel. `repo` and `path` are matched against the current status rather than trusted, so anything the status does not list is `404`. Read-only: it passes `--no-ext-diff --no-textconv` (no external diff or textconv driver runs), but a repository's clean filters still run, as they do for any `git diff`, which is why a repository a container can write to is never inspected (below). Capped at 400 KB, and refused (`400`) for remote and Docker sessions; a repository at or inside a Docker case workspace is not in the status, so it is `404` here.
@@ -1175,6 +1175,12 @@ Both routes accept two optional query parameters, which the UI sends from its pe
Lists are capped (300 files and 50 commits per repository) while the counts stay exact. A branch with no upstream reports the commits no remote has (`HEAD --not --remotes`); a repository with no remote reports `unpushedCount: 0`, since there is nothing to push to. Concurrent polls of one folder share a single git invocation; `?fresh=1` (what the panel's Refresh button and opening the panel send) skips the short-lived caches, though it still joins a computation already running.
`POST /api/sessions/:id/git-fetch` is the panel's **Fetch** button: one `git fetch --quiet` per repository the panel would show, through the same resolver so the two cannot disagree about which repositories belong to a workspace, with the same `maxRepos` and `timeout` clamps. It is the only git command the Git panel runs that writes — cloning and worktree management write too, but only when you asked for them at the moment you asked — and it writes remote-tracking refs only — nothing commits, checks out, merges or touches the working tree. It is not quite as harmless as a read: a fetch holds git's ref lock, so an agent's own `git pull` in the same clone can hit the same `cannot lock ref` while a fetch is running, which is why one folder is fetched by one run at a time. It runs on that click, or on the interval below and never otherwise, and `git fetch` is exactly the command that can run a repository's own hooks (`reference-transaction`, `pre-auto-gc` through the automatic maintenance a fetch triggers, and config commands such as `credential.helper`), which is why nothing runs on a timer until you opt in, and why a repository at or inside a Docker case workspace is refused before any git runs. Remote and Docker sessions answer `state: 'unsupported'` like the status route. Bounded: 4 repositories at a time across the whole run (one shared bound, not one per repository group — a scheduled tick keeps that one bound for all its folders, so 4 folders do not mean 4 × 4, and works at most 4 folders at a time), one spawn per repository with the same per-command timeout, which reaches the whole process group rather than only the `git` parent (a fetch over http spawns helper processes, and a timeout that signals the parent alone can leave one running after the answer goes out), `GIT_TERMINAL_PROMPT=0` plus BatchMode ssh so a repository that needs a login fails fast instead of hanging the request on an invisible prompt — Codeman supplies no credentials, so a repository your own git is already signed in to works because that is your existing setup. That BatchMode ssh is a default, never an override: your own `GIT_SSH_COMMAND` and the repository's `core.sshCommand` are honoured, and ⚠️ the default's `StrictHostKeyChecking=accept-new` records an unknown host key in `~/.ssh/known_hosts` without asking — BatchMode stops a prompt, not a write. A click joins a run already going for the same folder, and the click publishes the trigger of the run it actually did — `click` when the click was the run, `interval` when it joined a tick already going, because a click that fetched nothing cannot report itself as the fetch — as the session's `gitFetch` state (below), so another tab open on the same folder sees the same run.
`data` is `{ state, repos, reposTruncated, repoLimit, fetchedAt }`, `repos[]` each `{ name, path, ok }` and, when it failed, `failure` (`{ code, message, stderr }`: the codes as in the clone failures, plus `NO_REMOTE`). A repository that could not be fetched keeps its row rather than being dropped. The panel shows the result under its list and then re-reads, so `behind` reflects what this fetch brought.
The interval is two **synced** settings in `PUT /api/settings` (`src/git-fetch-scheduler.ts`): `gitFetchEnabled` (default `false`) and `gitFetchIntervalSeconds` (30 to 3600, default 300, the gap between runs timed from the start of a run so a slow repository does not push the next one out). Synced, not per-device, because the server is what acts on them; the scheduler reads them fresh on each 15 s tick, so a change works without a restart. A session can override both, and the override wins even while the app-wide switch is off: `POST /api/sessions/:id/git-fetch-settings` takes `{ "enabled": true | false | null, "intervalSeconds": number | null }` — `null` on a field clears that half so the app value applies again, a field left out of the body leaves the other half as it was — is `400 INVALID_INPUT` for a remote or Docker session, and answers `200` with `{ gitFetchSettings: { enabled, intervalSeconds } }` where `null` means the session follows the app. What the last run did rides the session state as `gitFetch` (`{ ranAt, trigger, state, repos, failed, firstFailure? }`, `trigger` is `click` or `interval`), on the existing `SessionUpdated` event: no new event. Sessions on the same folder share one run and both see its result, the schedule is keyed by folder, and a folder is fetched by at most one run at a time; a folder is due when ANY session open on it is due, so the order the sessions were read cannot decide which interval wins, and the folder is probed once for the whole group rather than once per session on it; every session open on a folder is remembered, so closing the one that holds the override does not stop that folder's fetching while another session is still open on it. The tick skips anything its bounded probe does not confirm is a directory, stamps each folder's schedule when it picks it, and does not run a second tick over a selection still going. Remote and Docker sessions are never fetched on a timer, and the Docker rule is re-checked against the CURRENT Docker roots every tick.
## Git worktrees of a case
A local case whose folder is the top of a git repository can keep **worktrees** at `<case>/.claude/worktrees/<name>`, each on its own branch, so several agents on one repository never share a checkout. This is the layout Claude Code's own `claude --worktree <name>` uses (branch `worktree-<name>`), so either tool finds the other's worktrees. Remote (SSH) and Docker cases are refused with `400 INVALID_INPUT` before git runs, and so is a local case whose folder is at or inside a Docker case workspace: `git worktree add` runs the repository's post-checkout hook and checkout filters on this machine, and a container can write there. A case folder that is not a repository, is a bare repository, or sits below the repository's top level is `400` too. The case resolves the way quick-start resolves it (a linked case is admin-only in multi-user mode, everything else is the caller's own case space; another user's case is `404`), and a case folder on a mount that does not answer is `422 OPERATION_FAILED`, never `404`.
+20 -2
View File
@@ -84,8 +84,26 @@ by folder** (per device, on by default) shows changed files under collapsed fold
window; off lists every file by its full path. **Git status: max repositories** (per device,
1 to 50, default 12) is how many repositories the window lists when a session's folder holds
several projects. **Git status: git timeout** (per device, 5 to 120 seconds, default 30) is how
long one git command may run before that repository is reported as unreadable; raise it for
repositories on a slow network share.
long one git command may run before that repository is reported as unreadable, and the same value
bounds the Git window's Fetch button; raise it for repositories on a slow network share.
**Git fetch on an interval** (synced, off by default) runs `git fetch` on a timer for the repositories the
Git window lists, so the `behind` number is current without a click, and **Git fetch: how often** (synced,
30 to 3600 seconds, default 300) is the gap between runs for a session that has no override of its own — timed from
the start of a run, so a slow repository does not push the next one out. These are the only Git settings
that are synced rather than per device, because the server's scheduler is what acts on them: kept per
device, the scheduler would read nobody's number. **Session Options → Git** overrides both the switch and
the interval for one session, and that override wins even while the app switch is off; a session that follows
the app shows the app's values and its rows go inert until you turn **Follow the app setting** off. Nothing is
ever fetched for a Docker or remote (SSH) session, and a repository a container can write to is refused
before any git runs. Sessions open on the same folder share one run, and a folder is fetched when ANY session open on it is due, so the order the sessions were read cannot decide which interval wins. Both default to off because `git fetch`
is the one git command the Git window runs that writes — cloning and worktree management write too, but only
when you asked for them at the moment you asked — and the one that can run a repository's own hooks
(`reference-transaction`, `pre-auto-gc` through the maintenance a fetch triggers, and config commands such as
`credential.helper`), and the one that can run later by itself, on a timer. The ssh it runs is BatchMode so
nothing waits for a login, and that is a default, never an override: your own `GIT_SSH_COMMAND`, or the
repository's `core.sshCommand`, is used when either is set. ⚠️ The default's `StrictHostKeyChecking=accept-new`
records an unknown host key in `~/.ssh/known_hosts` without asking — BatchMode stops a prompt, not a write.
Most default to off. The stock desktop header is system stats, File Viewer, Tiles, and the gear.
**Header Stats Style** picks how the system stats and plan usage are drawn: *Compact*
+24 -5
View File
@@ -245,12 +245,31 @@ Click it for a draggable window, in the style of the File Viewer:
left out; the **git timeout** setting raises how long it waits. They all start collapsed (each summary line shows its branch and
what is outstanding), and the ones you open stay open when the window refreshes; an unrelated repository above the workspace (a dotfiles repo
in your home folder) is ignored.
- **Fetch** in the header runs `git fetch` for the repositories the window lists, on your click; the
window then re-reads, so "behind" is as of that fetch. A repository that could not be fetched keeps
its row and shows why. **Git fetch on an interval** (Settings → Bottom bar, off by default) runs the
same fetch on a timer for every session that is on, and **Session Options → Git** overrides both the
switch and the interval for one session — a session that turned itself on runs even while the app-wide
switch is off, sessions open on the same folder share one run, and nothing is ever fetched for Docker or
remote (SSH) sessions.
It is read-only and offline: Codeman never fetches, commits or changes the repository, so
"behind" is as of your last fetch. It is not shown for Docker or remote (SSH) sessions, and a repository at or inside a Docker case
workspace is skipped even from a local session (a container can write there, and git would run
that repository's own configuration on the host). The
data comes from `GET /api/sessions/:id/git-status` and `GET /api/sessions/:id/git-diff`
It is read-only apart from that fetch: Codeman never commits, checks out or changes the
repository, and `git fetch` writes remote-tracking refs only — it is the only git command the Git window
runs that writes, the only one that can run a repository's own hooks (`reference-transaction`,
`pre-auto-gc` through the maintenance a fetch triggers, and config commands such as `credential.helper`),
and the only one that can run later by itself, on a timer: cloning and worktree management write too, but
only when you asked for them at the moment you asked, which is why nothing runs on a timer until you opt in. A fetch holds git's ref lock, so an agent's own `git pull` in the same repository
can hit the same `cannot lock ref`, and a folder is fetched by one run at a time. It is not shown for Docker
or remote (SSH) sessions, and a repository at or inside a Docker case
workspace is skipped even from a local session, before any git runs (a container can write there,
and git would run that repository's own configuration on the host). Fetch asks nothing of you: it
uses the sign-in your own git already has, and it gives up quickly rather than waiting on an
invisible login prompt. That BatchMode ssh is a default, never an override: your own
`GIT_SSH_COMMAND`, or the repository's `core.sshCommand`, is used when either is set, and ⚠️ the default's
`StrictHostKeyChecking=accept-new` records an unknown host key in `~/.ssh/known_hosts` without asking —
BatchMode stops a prompt, not a write. The
data comes from `GET /api/sessions/:id/git-status`, `GET /api/sessions/:id/git-diff` and, on that
click or the interval you turned on, `POST /api/sessions/:id/git-fetch`
(see the [API reference](https://github.com/Ark0N/Codeman/blob/master/docs/api-reference.md)).
## Gotchas
+11
View File
@@ -70,6 +70,17 @@ export const SESSION_LIMIT_WAIT_MS = 5000;
/** Pause between scheduled run iterations (ms) */
export const ITERATION_PAUSE_MS = 2000;
// ============================================================================
// Git Fetch Interval
// ============================================================================
/**
* How often the fetch scheduler (src/git-fetch-scheduler.ts) wakes to check which sessions are due (ms). A
* run lands within one tick of the interval the user set, because the interval is timed from the start of
* a run; a tick is a settings read and a due check, not a spawn, so a quiet install costs nothing.
*/
export const GIT_FETCH_TICK_INTERVAL_MS = 15 * 1000;
// ============================================================================
// Mux Stats
// ============================================================================
+262
View File
@@ -0,0 +1,262 @@
/**
* @fileoverview Git fetch on an interval: the sessions the user turned on, fetched by a tick the server owns
* (`src/git-fetch-scheduler.ts`, wired in `src/web/server.ts`).
*
* The fetch module (src/git-fetch.ts) is the only git command the Git panel runs that writes, and on a timer
* it is the only one that can run without being asked — cloning and worktree management write too, but those
* happen when the user asks for them. Which is why the whole feature is off until the user turns it on, in
* Settings → Bottom bar, per session in Session Options → Git.
*
* The scheduler holds no timers of its own. The server ticks it (`GIT_FETCH_TICK_INTERVAL_MS`) and every
* tick reads the app setting FRESH, so a live toggle takes effect on the next tick instead of at boot, and
* turning the feature off actually stops the fetching. A session can override both the switch and the
* interval; a session with no override follows the app.
*
* Rules the code keeps and the tests pin:
* - Nothing runs when nothing is on: no repository set is read and nothing is spawned, so a quiet
* install costs one settings read per tick. A session that turned itself on still runs even while the
* app-wide switch is off — that is what a per-session switch has to mean.
* - Remote and Docker sessions are never fetched, exactly as the Git panel excludes them, and the Docker
* workspace roots are checked again every tick, so a session whose case became a Docker case stops
* fetching at the next tick.
* - A folder is fetched by at most one run at a time, and the run belongs to the FOLDER, not to one
* session: two sessions open on the same folder are the same clone, so they share one run and both get
* its result. State is keyed by `resolve(workingDir)` — deliberately not `realpath`, because `realpath`
* is itself one of the unbounded fs calls rule #516 bounds; the bounded probe below is the fs read.
* Every session open on a folder is remembered, so closing the one holding the override does not stop
* the folder's fetching while another session is still on it. A folder is due when ANY session open on it
* is due, and the tick decides that per folder in a second pass: the order the sessions were read cannot
* change which interval wins, so a 30 s session on a folder a 3600 s session last fetched ten minutes ago
* is fetched now. The folder is probed once, not once per session on it.
* - Before anything is fetched, the folder is probed BOUNDED with the default options (rule #516): a case
* on a mount that stopped answering is skipped, never touched, and a probe that answers `unknown` is not
* read as "not a folder".
* - A schedule is stamped at SELECTION, when a session goes into `due`, not when its run starts, so a
* tick that is still running cannot pick the same folder again; and a tick is skipped while the previous
* one is still going, so the bound below is the bound for the whole tick, not per tick.
* - At most `FETCH_CONCURRENCY` git processes at a time across the whole tick, because each is a git
* process: ONE bound is shared by every run of the tick, so `FETCH_CONCURRENCY` is the tick's ceiling
* rather than each folder's own. The folders get their OWN bound (`mapLimited`), because one semaphore
* cannot serve both levels: a folder that holds a slot and then waits for one for its own fetch is
* waiting on itself, and the folders that fill the bound are exactly the ones blocking it.
* - The interval is timed from the START of a run, so a run that takes three minutes does not push the
* next one out by three minutes; it lands on the tick after its own interval elapses.
* - The per-repository limit and the git timeout stay the module's defaults (`MAX_REPOS`,
* `DEFAULT_GIT_TIMEOUT_MS`): both settings are per device and never reach the server, so the server
* cannot know what a device chose.
* - A failure is reported, not retried harder: the folder keeps its schedule and gets its next run at its
* own interval. A settings read that fails skips this tick only, because settings.json is rewritten in
* place and a kept fallback would hold the feature off until the next settings change.
*
* @module git-fetch-scheduler
*/
import { resolve } from 'node:path';
import { getErrorMessage } from './types.js';
import {
FETCH_CONCURRENCY,
MAX_GIT_FETCH_INTERVAL_SECONDS,
MIN_GIT_FETCH_INTERVAL_SECONDS,
gitFetchStatusFrom,
type GitFetchOptions,
type GitFetchRun,
type GitFetchSettings,
type GitFetchStatus,
type GitFetchTrigger,
} from './git-fetch.js';
import { clampInt, DEFAULT_GIT_TIMEOUT_MS, MAX_REPOS, createLimiter, mapLimited } from './git-workspace-status.js';
import type { PathProbeKind } from './utils/bounded-path-probe.js';
/** What the scheduler needs from a session: the facts a decision needs, and nothing else. */
export interface GitFetchSessionView {
id: string;
workingDir: string;
/** `unknown`, not `boolean`: a session's remote/Docker markers are objects, and the only question here is whether either is set at all. */
remote?: unknown;
docker?: unknown;
gitFetchEnabled?: boolean;
gitFetchIntervalSeconds?: number;
}
/** A session open on a folder, with the interval that makes IT due. One folder's sessions are a group. */
interface GroupMember {
view: GitFetchSessionView;
intervalSeconds: number;
}
export interface GitFetchPorts {
sessionIds(): Iterable<string>;
getSession(id: string): GitFetchSessionView | undefined;
/** Read FRESH every tick; that is the whole point of the tick-driven shape. */
readSettings(): Promise<GitFetchSettings>;
dockerWorkspaces(): Promise<string[]>;
/**
* Bounded probe (rule #516), default options: a bulk scan keeps the stall cap, so this must not be called
* with `pastCap`. Anything that is not `directory` — including `unknown`, which is never `absent` — is
* skipped, not fetched.
*/
probePath(path: string): Promise<PathProbeKind>;
/** Called through `fetchWorkspaceOnce`, so a run already going for this folder is joined, not stacked. */
fetch(cwd: string, opts: GitFetchOptions, trigger: GitFetchTrigger): Promise<GitFetchRun>;
publish(id: string, status: GitFetchStatus): void;
log?(message: string): void;
}
/**
* What one session will actually do: its own override wins, otherwise the app-wide setting. The interval is
* clamped again here because a persisted value can predate the schema's bounds.
*/
export function effectiveGitFetch(
view: GitFetchSessionView,
settings: GitFetchSettings
): { enabled: boolean; intervalSeconds: number } {
return {
enabled: view.gitFetchEnabled ?? settings.enabled,
intervalSeconds: clampInt(
view.gitFetchIntervalSeconds ?? settings.intervalSeconds,
MIN_GIT_FETCH_INTERVAL_SECONDS,
MAX_GIT_FETCH_INTERVAL_SECONDS,
MIN_GIT_FETCH_INTERVAL_SECONDS
),
};
}
export class GitFetchScheduler {
private readonly ports: GitFetchPorts;
/** When each FOLDER last started a run; timed from the start, not the end. */
private readonly lastRunAt = new Map<string, number>();
private readonly inFlight = new Set<string>();
/** Session → folder, so `remove()` can keep the folder's schedule while other sessions are still on it. */
private readonly folderOf = new Map<string, string>();
private running = false;
private stopped = false;
constructor(ports: GitFetchPorts) {
this.ports = ports;
}
/** One tick: fetch every folder whose sessions are on and due. Returns how many folders ran. */
async tick(now = Date.now()): Promise<number> {
if (this.stopped || this.running) return 0;
this.running = true;
try {
let settings: GitFetchSettings;
try {
settings = await this.ports.readSettings();
} catch (err) {
// A read can land mid-write. Skipping this tick costs one interval; deciding from a fallback would
// hold the feature off until the next settings change.
this.ports.log?.(`git fetch: settings unreadable, tick skipped: ${getErrorMessage(err)}`);
return 0;
}
// Pass 1 — who is on what, before anything is decided. Every session open on a folder is recorded here,
// not only the one that would get picked, so `remove()` can still see who is open on it when the session
// holding the override is the one that closes.
const groups = new Map<string, GroupMember[]>();
for (const id of this.ports.sessionIds()) {
const view = this.ports.getSession(id);
if (!view || view.remote || view.docker) continue;
const effective = effectiveGitFetch(view, settings);
if (!effective.enabled) continue;
const folder = resolve(view.workingDir);
this.folderOf.set(id, folder);
const group = groups.get(folder);
const member = { view, intervalSeconds: effective.intervalSeconds };
if (group) group.push(member);
else groups.set(folder, [member]);
}
// Pass 2 — the folder's turn, decided from the whole group rather than from whichever session happened to
// be read first. A folder is due when ANY session open on it is due: a session on a 30 s interval on a
// folder a 3600 s session last fetched ten minutes ago has to be fetched now, because that same run
// satisfies the long interval too. Deciding in one pass means the session read first owns the clock — a
// group ordered [short, long] and a group ordered [long, short] would have behaved differently, and the
// run belongs to the folder, so no session in the group should.
const due = new Map<string, GroupMember[]>();
for (const [folder, group] of groups) {
if (this.inFlight.has(folder)) continue;
const started = this.lastRunAt.get(folder);
const isDue = started === undefined || group.some((m) => now - started >= m.intervalSeconds * 1000);
if (!isDue) continue;
// Bounded probe (rule #516), once per folder rather than once per session on it.
const kind = await this.ports.probePath(folder);
if (kind !== 'directory') {
this.ports.log?.(`git fetch: ${folder} skipped, answered ${kind}`);
continue;
}
this.inFlight.add(folder);
// The clock starts at the selection, so a slow folder does not shift its own schedule.
this.lastRunAt.set(folder, now);
due.set(folder, group);
}
if (!due.size) return 0;
// Only now, because nothing above needs it: a quiet tick does not read the Docker case list.
const dockerWorkspaces = await this.ports.dockerWorkspaces();
// ONE bound for the git processes of the whole tick, handed to every run so no folder gets its own:
// each fetch is one git process, and a folder can hold up to `MAX_REPOS_LIMIT` of them, so a bound per
// run would let `FETCH_CONCURRENCY` folders × `MAX_REPOS_LIMIT` processes run at once.
const fetches = createLimiter(FETCH_CONCURRENCY);
// The folders get their OWN bound, because the same semaphore cannot serve both levels: a folder that
// holds a slot and then waits for a slot for its own fetch is waiting on itself — once
// `FETCH_CONCURRENCY` folders fill the bound, the ones holding slots are exactly the ones that can
// never get one back. Both bounds are `FETCH_CONCURRENCY`, so the tick still never runs more git
// processes than the module's ceiling.
await mapLimited([...due.entries()], FETCH_CONCURRENCY, async ([folder, group]) => {
try {
const run = await this.ports.fetch(
folder,
{
dockerWorkspaces,
maxRepos: MAX_REPOS,
timeoutMs: DEFAULT_GIT_TIMEOUT_MS,
limiter: fetches,
},
'interval'
);
// Every session on the folder gets the SAME run, with the trigger of the run that actually happened:
// if this tick joined a run a click had already started, the row has to say it was a click, because
// that is what fetched it.
for (const member of group) this.ports.publish(member.view.id, gitFetchStatusFrom(run.report, run.trigger));
} catch (err) {
// The run that failed keeps its reason in the panel's own row; here only the folder-level failure is
// worth a line, because nothing else would say a scheduled fetch could not run at all.
this.ports.log?.(`git fetch: ${folder} could not run: ${getErrorMessage(err)}`);
} finally {
this.inFlight.delete(folder);
}
});
return due.size;
} finally {
this.running = false;
}
}
/**
* A session that closed or was detached: its schedule goes with it, but the FOLDER's stays while another
* session is still open on it — the run belongs to the clone, not to the session that asked for it.
*/
remove(id: string): void {
const folder = this.folderOf.get(id);
this.folderOf.delete(id);
if (!folder) return;
const stillOpen = [...this.folderOf.values()].includes(folder);
if (!stillOpen) {
this.lastRunAt.delete(folder);
this.inFlight.delete(folder);
}
}
stop(): void {
this.stopped = true;
this.lastRunAt.clear();
this.inFlight.clear();
this.folderOf.clear();
}
/** Folders the scheduler still remembers a run for, so a test can see a `remove()` actually took. */
tracked(): number {
return new Set([...this.lastRunAt.keys(), ...this.inFlight]).size;
}
}
+506
View File
@@ -0,0 +1,506 @@
/**
* @fileoverview `git fetch` for the repositories the Git panel shows, on the user's click
* (`POST /api/sessions/:id/git-fetch`) or on an interval the user turned on
* (`src/git-fetch-scheduler.ts`).
*
* The status module (src/git-workspace-status.ts) is deliberately offline: "behind" is as of the last
* fetch, so a number that is stale can only be made current by fetching. This is the only git command the
* Git panel runs that writes, and the only git command Codeman runs on a timer. Cloning a repository and
* managing worktrees write too, but those are things the user asked for at the moment they asked; this is
* the one that can happen later, by itself. Nothing here commits, checks out, merges or touches the working
* tree: `git fetch` updates remote-tracking
* refs and nothing else, and `FETCH_CONFIG_ARGS` keeps it from starting a gc in a repository an agent is
* already using. It is not harmless in the way a read is: a fetch holds git's ref lock, so an agent's own
* `git pull` in the same clone can collide with it (`cannot lock ref`), which is why one folder is fetched
* by at most one run at a time (`fetchWorkspaceOnce`).
*
* Same split as git-clone.ts: the pure half (`buildFetchArgs`, `describeFetchFailure`, `fetchEnvFor`,
* `gitFetchSettingsFrom`, `gitFetchStatusFrom`) holds every decision and tests without spawning, and the IO
* half runs one bounded `git fetch --quiet` per repository.
*
* Rules the code keeps and the tests pin:
* - The repository set is `resolveWorkspaceRepos`, the single source the panel and the diff route
* already use, so Fetch cannot reach a repository the panel would not show. The Docker rule is
* checked before any git runs: a repository a container can write to is refused outright, because a
* planted config would run on the host — and `git fetch` is exactly the command that can run a
* repository's own hooks (`reference-transaction`, and `pre-auto-gc` through the automatic maintenance
* that follows a fetch) and its config commands such as `credential.helper`, which is why a timer only
* runs it after the user opts in.
* - One run per folder at a time: `fetchWorkspaceOnce` joins a run already going for the same folder
* instead of starting a second one, because two fetches in one clone collide on the ref lock.
* - Bounded: the git timeout from Settings → Bottom bar per repository, `MAX_REPOS_LIMIT` repositories at
* most, a hard wall-clock bound on each spawn, and `FETCH_CONCURRENCY` git processes at a time for the
* whole run — one `Limiter`, shared by the scheduler's tick, not one bound per folder.
* - Non-interactive: `GIT_TERMINAL_PROMPT=0` and BatchMode ssh, so a private repository that needs a
* login fails fast instead of hanging the request on an invisible username prompt. Codeman collects
* no credentials; a repository the user's own git is already signed in to works because that is the
* user's existing setup, so unlike a clone no credential helper is disabled here. That BatchMode ssh is
* a default, never an override: `fetchEnvFor` keeps whatever the repository's `core.sshCommand`, the
* user's own `GIT_SSH_COMMAND` or a `GIT_SSH` already says, because on a machine with several ssh setups
* that choice is usually the one that works. ⚠️ The default still leaves a record: `StrictHostKeyChecking=accept-new`
* writes an unknown host key into `~/.ssh/known_hosts` without asking — BatchMode stops a prompt, not a
* write.
* - The timeout kills the PROCESS GROUP, not just the `git` parent. A fetch over http spawns
* `git-remote-http` children, and `execFile`'s `timeout` signals the parent only, so the answer can go
* out while a helper is still running — and on a timer that repeats every tick with nobody watching.
* `spawn` with `detached: true` puts the tree in its own group so the escalation (SIGTERM, then SIGKILL
* `FETCH_KILL_ESCALATION_MS` later) reaches the children too, which is why the negative pid is used
* rather than `child.kill()`. Same shape as `runGit` in git-clone.ts, without that module's slot queue:
* fetch is bounded by `FETCH_CONCURRENCY`, not by a clone queue.
* - Failure text reaching a client is control-stripped and credential-redacted (`sanitizeGitOutput`),
* and the browser writes it with `textContent` only.
*
* @module git-fetch
*/
import { execFile, spawn } from 'node:child_process';
import { basename, relative, resolve } from 'node:path';
import { promisify } from 'node:util';
import { classifyGitFailure, gitNonInteractiveEnv, sanitizeGitOutput, type GitFailureCode } from './git-clone.js';
import {
createLimiter,
DEFAULT_GIT_TIMEOUT_MS,
type Limiter,
resolveOverviewLimits,
resolveWorkspaceRepos,
type GitRunner,
} from './git-workspace-status.js';
const execFileAsync = promisify(execFile);
/**
* Git processes in flight at once, for one run — and for a whole scheduler tick, because the tick hands ONE
* bound to every run (see `createLimiter`): each fetch is one git process, and a folder can hold up to
* `MAX_REPOS_LIMIT`. The tick bounds its folders separately, because the same semaphore cannot serve both
* levels — a folder holding a slot would then wait for a slot its own fetch needs.
*/
export const FETCH_CONCURRENCY = 4;
/** A fetch on a busy remote can print a lot; a bound on what we will hold. */
const MAX_FETCH_OUTPUT_BYTES = 2 * 1024 * 1024;
/** git's stderr is kept as a bounded tail (as in git-clone.ts): enough for the reason, not the whole stream. */
const MAX_FETCH_STDERR_BYTES = 8_192;
/** A `git config --get` answer is one line; this is a sanity cap, not an expected size. */
const MAX_SSH_COMMAND_BYTES = 4_096;
/**
* How long the process group gets to answer SIGTERM before the same escalation goes to SIGKILL. Kept as a
* const so a test can say how long it is willing to wait for the group to actually die.
*/
export const FETCH_KILL_ESCALATION_MS = 3_000;
/**
* Config overrides set ahead of the argv, so an unattended fetch cannot do more than move refs: no
* fsmonitor hook, and no automatic maintenance or gc. A fetch is the git command that can run a
* repository's own hooks (`reference-transaction`, and `pre-auto-gc` through the maintenance that follows a
* fetch), and a gc started by a timer in a repository an agent is working in is exactly the kind of extra
* write this module must not do. Kept as a const so a test can pin it without spawning git.
*/
export const FETCH_CONFIG_ARGS = ['-c', 'core.fsmonitor=false', '-c', 'maintenance.auto=false', '-c', 'gc.auto=0'];
/** The interval the user can turn on (Settings → Bottom bar, and Session Options → Git): bounds and default. */
export const DEFAULT_GIT_FETCH_INTERVAL_SECONDS = 300;
export const MIN_GIT_FETCH_INTERVAL_SECONDS = 30;
export const MAX_GIT_FETCH_INTERVAL_SECONDS = 3600;
export interface GitFetchSettings {
enabled: boolean;
intervalSeconds: number;
}
/**
* A settings object as the scheduler should read it: absent means OFF, because nothing runs on a timer
* until the user turns this on, and a number outside the schema's bounds is clamped rather than trusted.
* Pure, so the reading itself is testable without a settings file.
*/
export function gitFetchSettingsFrom(settings: Record<string, unknown> | undefined): GitFetchSettings {
const raw = settings?.gitFetchIntervalSeconds;
const seconds =
typeof raw === 'number' && Number.isFinite(raw) ? Math.round(raw) : DEFAULT_GIT_FETCH_INTERVAL_SECONDS;
return {
enabled: settings?.gitFetchEnabled === true,
intervalSeconds: Math.min(MAX_GIT_FETCH_INTERVAL_SECONDS, Math.max(MIN_GIT_FETCH_INTERVAL_SECONDS, seconds)),
};
}
/**
* The only git command this module runs. Kept as a function so a test can pin the verb: nothing here
* commits, checks out, merges or prunes, and no operand is interpolated — the repository is the process
* `cwd` and the argv is fixed.
*/
export function buildFetchArgs(): string[] {
return ['fetch', '--quiet'];
}
/**
* The `git` process also gets the `FETCH_CONFIG_ARGS` overrides ahead of this argv; they are kept separate
* so pinning the verb here does not have to say anything about maintenance, and so both can be tested
* without spawning.
*
* A repository with no remote is a fact, not a fault. Git's wordings for it differ by version — 2.47
* exits quietly and this code is never reached, older git says "no default remote repository" — so the
* branch is pinned on literal fixtures and the code the panel shows is the code this writes.
*/
export type FetchFailureCode = GitFailureCode | 'NO_REMOTE';
export interface FetchFailure {
code: FetchFailureCode;
/** User-facing summary. */
message: string;
/** Tail of git's own stderr, control-stripped and credential-redacted. */
stderr: string;
}
/**
* A thrown git error as the panel should show it. `classifyGitFailure` (git-clone.ts) already knows the
* network reasons — auth, an unreachable host, a missing git — so they are reused here; only its timeout
* wording is written for clones, so the fetch path replaces it with what the user can actually do.
*/
export function describeFetchFailure(err: unknown): FetchFailure {
const e = err as { code?: unknown; stderr?: unknown; message?: string; killed?: boolean };
const stderr = typeof e.stderr === 'string' ? e.stderr : '';
const spawnError = typeof e.message === 'string' ? e.message : undefined;
const clean = sanitizeGitOutput(stderr);
const lower = `${clean}\n${spawnError ?? ''}`.toLowerCase();
if (/no default remote repository|no remote configured|nothing to fetch/.test(lower)) {
return {
code: 'NO_REMOTE',
message: 'This repository has no remote, so there is nothing to fetch.',
stderr: clean,
};
}
const timedOut = e.code === 'ETIMEDOUT' || e.killed === true;
const failure = classifyGitFailure(stderr, timedOut, spawnError);
if (failure.code === 'TIMEOUT')
failure.message = 'Git timed out. Raise “Git status: git timeout” in Settings → Bottom bar, or fetch from a shell.';
return failure;
}
/**
* The environment a fetch gets, as a pure decision so it can be pinned without spawning git.
*
* `gitNonInteractiveEnv` supplies the BatchMode default, and the default is only a default: git reads
* `GIT_SSH_COMMAND` from the environment ahead of the repository's `core.sshCommand`, so setting it would
* override a repository that already chose its own ssh — an alternative host, an identity file, a jump box —
* and break a setup that works today. The server's own `GIT_SSH` is the same kind of answer: git reads it
* after both of those (`GIT_SSH_COMMAND`, then `core.sshCommand`, then `GIT_SSH`), so a written default would
* hide it too. That is the only case where this module makes an ssh choice on the user's behalf, so it is the
* whole decision here: the caller supplies the value it read, and this decides between the user's
* environment and the repository's own answer.
*/
export function fetchEnvFor(base: NodeJS.ProcessEnv, repoSshCommand: string | null): NodeJS.ProcessEnv {
const env = gitNonInteractiveEnv(base);
// `gitNonInteractiveEnv` only writes the default when the environment had nothing, so this is exactly the
// case where it was a choice rather than a pass-through, and the repository's own answer, or a `GIT_SSH` in
// the environment, wins over it.
if (!base.GIT_SSH_COMMAND && (repoSshCommand || base.GIT_SSH)) delete env.GIT_SSH_COMMAND;
return env;
}
/**
* The repository's own `core.sshCommand`, or null. One bounded, read-only `git config --get` per fetch:
* git would honour that config itself if we did not write `GIT_SSH_COMMAND` over it, so honouring it means
* not writing one. `--get` reads local and global config, which is the value git would have used, and no
* hook or filter runs on the way to it.
*
* The read happens inside the same slot and the same wall-clock bound as the fetch it serves, so it cannot
* add a fifth git process or push a fetch past the user's timeout — it spends part of it.
*/
export async function readRepoSshCommand(cwd: string, timeoutMs: number): Promise<string | null> {
try {
const { stdout } = await execFileAsync('git', ['config', '--get', 'core.sshCommand'], {
cwd,
timeout: timeoutMs,
maxBuffer: MAX_SSH_COMMAND_BYTES,
env: gitNonInteractiveEnv(),
});
return stdout.trim() || null;
} catch {
// A repository with no such setting, or a read that could not finish: the default is what git would have
// used anyway, and a fetch must not fail because the check for a config value failed.
return null;
}
}
/**
* Fetch is allowed to write refs, so this runner does not carry `--no-optional-locks`: fetch takes a
* required lock anyway.
*
* `spawn`, not `execFile`, because the bound has to reach the whole tree (see the fileoverview): the
* caller is answered at the timeout, and the SIGTERM → SIGKILL escalation is deliberately NOT cancelled
* when the answer goes out, because the promise is a promise about the answer while the group still has to
* die. That is the difference from `runGit` in git-clone.ts, which disarms the escalation at `finish` and so
* can leave a `git-remote-http` child running after a timed-out call.
*
* The thrown error keeps the shape `describeFetchFailure` reads: `stderr` for the reason, `message` for a
* spawn failure (`spawn git ENOENT` → GIT_MISSING), `killed` and `code` for the timeout. A non-zero exit
* rejects the way `execFile` would — `code` is then the exit code — because resolving it would report a real
* failure as a clean run with an empty reason.
*
* `timeoutMs` bounds the `core.sshCommand` read and the fetch TOGETHER: the spawn is armed with what the read
* left, so a `git` that never answers costs one timeout, not two. A read that used the whole bound answers
* as a timeout without starting the fetch.
*/
export const runFetch: GitRunner = async (cwd, args, opts) => {
const timeoutMs = opts?.timeoutMs ?? DEFAULT_GIT_TIMEOUT_MS;
const startedAt = Date.now();
const env = fetchEnvFor(process.env, await readRepoSshCommand(cwd, timeoutMs));
const remainingMs = timeoutMs - (Date.now() - startedAt);
if (remainingMs <= 0) {
throw Object.assign(new Error(`Command failed: git ${args.join(' ')}`), {
stderr: '',
killed: true,
code: 'ETIMEDOUT',
});
}
return new Promise<string>((resolve, reject) => {
let child: ReturnType<typeof spawn>;
try {
child = spawn('git', [...FETCH_CONFIG_ARGS, ...args], {
cwd,
env,
stdio: ['ignore', 'pipe', 'pipe'],
detached: true,
});
} catch (err) {
reject(err);
return;
}
let stdout = '';
let stderr = '';
let stdoutBytes = 0;
let timedOut = false;
let settled = false;
let killTimer: NodeJS.Timeout | undefined;
const killTree = (signal: NodeJS.Signals) => {
try {
if (child.pid) process.kill(-child.pid, signal);
} catch {
try {
child.kill(signal);
} catch {
/* already gone */
}
}
};
const fail = (spawnError?: string, exitCode?: number | null) => {
if (settled) return;
settled = true;
// Only the timeout timer is disarmed here. On a timeout the escalation is what the caller is waiting
// for, and cancelling it is the bug this runner exists to fix.
clearTimeout(timeoutTimer);
reject(
Object.assign(new Error(spawnError ?? `Command failed: git ${args.join(' ')}`), {
stderr,
killed: timedOut,
code: timedOut ? 'ETIMEDOUT' : (exitCode ?? undefined),
})
);
};
const timeoutTimer = setTimeout(() => {
timedOut = true;
killTree('SIGTERM');
killTimer = setTimeout(() => killTree('SIGKILL'), FETCH_KILL_ESCALATION_MS);
fail();
}, remainingMs);
child.stdout?.on('data', (chunk: Buffer) => {
stdoutBytes += chunk.length;
if (stdoutBytes <= MAX_FETCH_OUTPUT_BYTES) stdout += chunk.toString('utf-8');
});
child.stderr?.on('data', (chunk: Buffer) => {
stderr += chunk.toString('utf-8');
if (stderr.length > MAX_FETCH_STDERR_BYTES * 2) stderr = stderr.slice(-MAX_FETCH_STDERR_BYTES);
});
const finish = (code: number | null) => {
if (settled) return;
// execFile's contract, which `describeFetchFailure` depends on: a non-zero exit rejects, so a real
// git failure keeps its reason in `stderr` instead of becoming a green row with an empty one. `null`
// means a signal, reachable only when something outside this runner killed the group — our own timeout
// has already answered by then, and `settled` above is what keeps that answer the answer.
if (code !== 0) return fail(undefined, code);
settled = true;
clearTimeout(timeoutTimer);
if (killTimer) clearTimeout(killTimer);
resolve(stdout);
};
child.on('error', (err) => fail(String(err)));
child.on('close', (code) => finish(code));
});
};
export interface GitFetchEntry {
/** Folder name of the repository (its root's basename), as the panel names it. */
name: string;
/** The repository root relative to the working directory: `.`, `..`, `api`, `apps/web`. */
path: string;
ok: boolean;
failure?: FetchFailure;
}
export interface GitFetchReport {
/** `ok` when at least one repository was fetched (or attempted); the other states are as in the overview. */
state: 'ok' | 'not-a-repo' | 'unsupported' | 'error';
reason?: 'remote' | 'docker';
error?: string;
/** One entry per repository fetched, in the same order the panel lists them. */
repos: GitFetchEntry[];
/** More than `repoLimit` repositories were found; only the first were fetched. */
reposTruncated: boolean;
/** The most repositories this fetch would list (the caller's setting, or `MAX_REPOS`). */
repoLimit?: number;
/** When the last repository finished, so the panel can say what the "behind" number is now based on. */
fetchedAt: number;
}
/**
* What one run did, in the shape a session keeps and the Session Options Git row shows. `trigger` says
* whether the user clicked or the interval fired, because a number the user did not ask for should read
* differently from one they did.
*/
/** What a run was, and why it happened. */
export type GitFetchTrigger = 'click' | 'interval';
export interface GitFetchStatus {
ranAt: number;
trigger: GitFetchTrigger;
/** As in the report: `ok`, or the state that stopped the run. */
state: GitFetchReport['state'];
/** Repositories this run covered. */
repos: number;
/** How many of them could not be fetched. */
failed: number;
/** The first failure, named: enough for one row without reprinting the whole list. */
firstFailure?: { name: string; code: FetchFailureCode };
}
/**
* One run, with the trigger that caused it. A joiner gets the run already going, so what it reports is that
* run's trigger rather than the one that made it ask: a click that joins an interval run did not fetch
* anything itself, and the row the panel shows has to describe the fetch that actually happened.
*/
export interface GitFetchRun {
report: GitFetchReport;
trigger: GitFetchTrigger;
}
export function gitFetchStatusFrom(report: GitFetchReport, trigger: GitFetchTrigger): GitFetchStatus {
const failed = report.repos.filter((r) => !r.ok);
const status: GitFetchStatus = {
ranAt: report.fetchedAt,
trigger,
state: report.state,
repos: report.repos.length,
failed: failed.length,
};
const first = failed[0];
if (first?.failure) status.firstFailure = { name: first.name, code: first.failure.code };
return status;
}
/** Options for the fetch path: the same repository rules and limits as an overview, without its cache clock. */
export interface GitFetchOptions {
git?: GitRunner;
home?: string;
dockerWorkspaces?: string[];
maxRepos?: number;
timeoutMs?: number;
/**
* The shared slot count for a whole scheduler tick. Passed in so `FETCH_CONCURRENCY` bounds the tick
* rather than each folder separately; without it, a tick over more than `FETCH_CONCURRENCY` folders could
* have that many git processes going at once inside each one.
*/
limiter?: Limiter;
}
export const emptyReport = (state: GitFetchReport['state'], extra: Partial<GitFetchReport> = {}): GitFetchReport => ({
state,
repos: [],
reposTruncated: false,
fetchedAt: Date.now(),
...extra,
});
async function fetchOne(dir: string, git: GitRunner, timeoutMs: number): Promise<FetchFailure | null> {
try {
await git(dir, buildFetchArgs(), { timeoutMs });
return null;
} catch (err) {
return describeFetchFailure(err);
}
}
/**
* Fetch every repository the panel would show for `cwd`, through the same resolver so the two cannot
* disagree. A repository that failed keeps its row with the reason, exactly as an unreadable repository
* stays in the status list: the panel must show that something was not fetched rather than quietly skip it.
*/
export async function fetchGitWorkspaceOverview(cwd: string, opts: GitFetchOptions = {}): Promise<GitFetchReport> {
const where = await resolveWorkspaceRepos(cwd, opts);
if (where.kind === 'docker') return emptyReport('unsupported', { reason: 'docker' });
if (where.kind === 'error') return emptyReport('error', { error: where.error });
const dirs = where.kind === 'enclosing' ? [where.root] : where.dirs;
if (!dirs.length) return emptyReport('not-a-repo');
const { timeoutMs } = resolveOverviewLimits(opts);
const runner = opts.git ?? runFetch;
const run = opts.limiter ?? createLimiter(FETCH_CONCURRENCY);
const failures = await run(dirs, (dir) => fetchOne(dir, runner, timeoutMs));
const repos: GitFetchEntry[] = dirs.map((dir, i) => {
const base = { name: basename(dir), path: relative(cwd, dir) || '.' };
const failure = failures[i];
return failure ? { ...base, ok: false, failure } : { ...base, ok: true };
});
return {
state: 'ok',
repos,
reposTruncated: where.kind === 'children' ? where.truncated : false,
repoLimit: resolveOverviewLimits(opts).maxRepos,
fetchedAt: Date.now(),
};
}
/**
* Runs already going, keyed by the resolved folder. A request for a folder another run is already working on
* JOINS that run instead of starting a second `git fetch` in the same clone: two fetches there collide on
* git's ref lock (`cannot lock ref 'refs/remotes/origin/main'`), which is what a click during a tick would
* otherwise do. A joiner gets the run already going's answer, including its limits and its trigger — the point
* is not to fetch twice, not to fetch with the freshest options, and a click that fetched nothing cannot
* report itself as the fetch.
*
* Keyed by `resolve`, not `realpath`, because `realpath` is itself one of the unbounded fs calls rule #516
* bounds for user-chosen paths; the scheduler probes the folder bounded and calls this. Two paths that
* resolve the same are the same folder here; a workspace reached through a symlink resolves to the link, so
* a link and its target can be fetched by two runs — the accepted trade for keeping the probe bounded.
*/
const lane = new Map<string, Promise<GitFetchRun>>();
export async function fetchWorkspaceOnce(
folder: string,
opts: GitFetchOptions = {},
trigger: GitFetchTrigger
): Promise<GitFetchRun> {
const key = resolve(folder);
const going = lane.get(key);
// The joiner is handed the run already going as it is, trigger included: it did not cause that fetch, so it
// must not report itself as having.
if (going) return going;
const run: Promise<GitFetchRun> = fetchGitWorkspaceOverview(key, opts)
.then((report) => ({ report, trigger }))
.finally(() => {
// Only the run that is still the lane's own: a later run for the same folder must not be dropped by an
// earlier one finishing late.
if (lane.get(key) === run) lane.delete(key);
});
lane.set(key, run);
return run;
}
/** Test seam: an in-memory lane is not cleared by stopping the scheduler, so a test has to clear it itself. */
export function clearGitFetchLane(): void {
lane.clear();
}
+55 -6
View File
@@ -22,7 +22,8 @@
*
* Rules the code keeps and the tests pin:
* - READ-ONLY and OFFLINE. It never fetches, pulls, commits or writes. "Behind" therefore reflects
* the last fetch (the UI says so); "ahead" and the unpushed list are exact against the
* the last fetch (the UI says so, and the Fetch button is a separate user-triggered path in
* `src/git-fetch.ts`, never a poll); "ahead" and the unpushed list are exact against the
* remote-tracking refs already on disk. `--no-optional-locks` keeps `git status` from even
* refreshing the index, so polling cannot contend with the agent's own git commands.
* - Every call is async (`execFile`), bounded by a timeout, and never interpolates a path into a
@@ -596,8 +597,55 @@ export async function discoverChildRepos(
const discoveryCache = new Map<string, { at: number; value: { dirs: string[]; truncated: boolean } }>();
/** Run `fn` over `items` with at most `limit` in flight, keeping the input order. */
async function mapLimited<T, R>(items: T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {
/**
* A slot count fixed ONCE, so callers share it instead of each getting its own bound (see the fetch path):
* the count lives in the closure, so `limit` is the ceiling for everything going through THIS limiter at
* once, not for each call to it — which is what makes a scheduler tick's bound honest.
* ⚠️ One limiter cannot bound two levels of the same work: a caller that holds a slot and then waits for
* another slot for the work IT starts cannot get one, because the holders are exactly the ones waiting. The
* outer level needs its own bound (`mapLimited`), which is why the tick shares one for fetches and keeps a
* separate one for folders.
*/
export type Limiter = <T, R>(items: T[], fn: (item: T) => Promise<R>) => Promise<R[]>;
export function createLimiter(limit: number): Limiter {
let inUse = 0;
const waiting: Array<() => void> = [];
const acquire = (): Promise<void> => {
if (inUse < limit) {
inUse++;
return Promise.resolve();
}
return new Promise<void>((done) => {
waiting.push(() => {
inUse++;
done();
});
});
};
const release = () => {
inUse--;
const next = waiting.shift();
if (next) next();
};
return async <T, R>(items: T[], fn: (item: T) => Promise<R>): Promise<R[]> => {
const out: R[] = new Array(items.length);
await Promise.all(
items.map(async (item, i) => {
await acquire();
try {
out[i] = await fn(item);
} finally {
release();
}
})
);
return out;
};
}
/** Run `fn` over `items` with at most `limit` in flight, keeping the input order. Per call; `createLimiter` shares one bound across calls. */
export async function mapLimited<T, R>(items: T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {
const out: R[] = new Array(items.length);
let next = 0;
const worker = async () => {
@@ -634,7 +682,7 @@ export function resolveOverviewLimits(opts: { maxRepos?: unknown; timeoutMs?: un
};
}
type WorkspaceRepos =
export type WorkspaceRepos =
| { kind: 'docker' }
| { kind: 'error'; error: string }
| { kind: 'enclosing'; root: string }
@@ -643,9 +691,10 @@ type WorkspaceRepos =
/**
* WHICH repositories belong to the workspace (the module header has the rules), without a full
* status of any of them: one cached `rev-parse` for the enclosing repository, else the cached scan
* below the folder. The overview and the diff route both go through here, so they cannot disagree.
* below the folder. The overview, the fetch route and the diff route all go through here, so they cannot
* disagree about which repositories belong to a workspace.
*/
async function resolveWorkspaceRepos(cwd: string, opts: GitOverviewOptions): Promise<WorkspaceRepos> {
export async function resolveWorkspaceRepos(cwd: string, opts: GitOverviewOptions): Promise<WorkspaceRepos> {
const now = opts.now ?? Date.now;
const { maxRepos, timeoutMs } = resolveOverviewLimits(opts);
const dockerRoots = await realAll(opts.dockerWorkspaces ?? []);
+20
View File
@@ -42,6 +42,7 @@ import { dataPath } from './config/instance.js';
import { readJsonConfig, SETTINGS_PATH } from './web/route-helpers.js';
import { isNearStalledPath, probePath } from './utils/index.js';
import { DEFAULT_KEEP_WARM_MAX_HOURS, type KeepWarmSettings } from './prompt-cache-keepwarm.js';
import { gitFetchSettingsFrom, type GitFetchSettings } from './git-fetch.js';
/**
* Existence check for a WRITER. Unlike the bounded read-side probe (`probePath`),
@@ -1173,6 +1174,25 @@ export async function readKeepWarmSettingsOrThrow(): Promise<KeepWarmSettings> {
return keepWarmSettingsFrom(JSON.parse(text) as Record<string, unknown>);
}
/**
* The Git fetch interval's app-wide default (`gitFetchEnabled`, absent = OFF) and its cap
* (`gitFetchIntervalSeconds`, seconds between runs). Read FRESH on every tick by the scheduler, so a live
* toggle takes effect on the next tick and turning it off actually stops the fetching. A missing file is
* the defaults — OFF — but any other read or parse failure rejects, for the same reason as
* {@link readKeepWarmSettingsOrThrow}: settings.json is rewritten in place, so a read can land mid-write,
* and a fallback kept from it would hold the feature off until the next settings change.
*/
export async function readGitFetchSettings(): Promise<GitFetchSettings> {
let text: string;
try {
text = await readFile(SETTINGS_PATH, 'utf-8');
} catch (err) {
if ((err as NodeJS.ErrnoException).code === 'ENOENT') return gitFetchSettingsFrom({});
throw err;
}
return gitFetchSettingsFrom(JSON.parse(text) as Record<string, unknown>);
}
function keepWarmSettingsFrom(settings: Record<string, unknown>): KeepWarmSettings {
const hours = settings?.promptCacheKeepWarmMaxHours;
return {
+49
View File
@@ -68,6 +68,7 @@ import {
type StatusLineExporter,
type KeepWarmStatus,
} from './types.js';
import type { GitFetchStatus } from './git-fetch.js';
import { resolveAndClaimOmpSessionId } from './utils/omp-session-resolver.js';
import { claudeTranscriptExists } from './utils/claude-transcript.js';
import { matchesPattern } from './config/cli-registry/patterns.js';
@@ -614,6 +615,12 @@ export class Session extends EventEmitter {
private _keepWarmEnabled: boolean | undefined;
/** Last status the keep-warm service published for this session; ephemeral. */
private _keepWarm: KeepWarmStatus | null = null;
/** Git fetch on an interval for this session; undefined = follow the app-wide default. Persisted. */
private _gitFetchEnabled: boolean | undefined;
/** Seconds between this session's fetch runs; undefined = follow the app-wide default. Persisted. */
private _gitFetchIntervalSeconds: number | undefined;
/** Last status the fetch scheduler published for this session; ephemeral. */
private _gitFetch: GitFetchStatus | null = null;
/** Until when the current turn counts as Codeman's own keep-alive (hooks open pre-acknowledged). */
private _keepAliveTurnUntil = 0;
/** Last keystroke a person sent through a `fromUser` write. */
@@ -926,6 +933,10 @@ export class Session extends EventEmitter {
lastRealPromptAt?: number;
/** Restored prompt-cache keep-warm choice (see `keepWarmEnabled`). */
keepWarmEnabled?: boolean;
/** Restored Git fetch override for this session (see `gitFetchEnabled`). */
gitFetchEnabled?: boolean;
/** Restored Git fetch interval for this session (see `gitFetchIntervalSeconds`). */
gitFetchIntervalSeconds?: number;
/** Restored conversation chain, oldest first (see `claudeSessionChain`). */
claudeSessionChain?: string[];
/** Restored agent-exit observation for this session's pane (see `paneExit`). */
@@ -1015,6 +1026,10 @@ export class Session extends EventEmitter {
// from before the field has only `lastSubmitAt`, and every submit then was a real one.
this._lastRealPromptAt = config.lastRealPromptAt ?? config.lastSubmitAt ?? 0;
this._keepWarmEnabled = config.keepWarmEnabled;
// Restored, like the keep-warm choice: the interval is the user's decision about their repositories
// and outlives the run that made it, so a restart keeps it rather than falling back to the app default.
this._gitFetchEnabled = config.gitFetchEnabled;
this._gitFetchIntervalSeconds = config.gitFetchIntervalSeconds;
// Restored chain: its tail is the conversation the CLI was actually on when
// the server stopped, which outranks the launch id seeded just above. The
// FIRST-HAND flag is deliberately NOT restored — a persisted claim is not a
@@ -1579,6 +1594,37 @@ export class Session extends EventEmitter {
return changed;
}
/** Git fetch override for this session; undefined means the app-wide setting applies. */
get gitFetchEnabled(): boolean | undefined {
return this._gitFetchEnabled;
}
/** Interval override for this session; undefined means the app-wide setting applies. */
get gitFetchIntervalSeconds(): number | undefined {
return this._gitFetchIntervalSeconds;
}
/**
* Set the session's override. The Session Options rows save on their own, so a caller passes what it has
* and leaves the other half as it was; `undefined` on either means the app-wide setting applies again.
*/
setGitFetchSettings(enabled: boolean | undefined, intervalSeconds: number | undefined): void {
this._gitFetchEnabled = enabled;
this._gitFetchIntervalSeconds = intervalSeconds;
}
/** What the fetch scheduler last reported for this session, or null before its first run. */
get gitFetch(): GitFetchStatus | null {
return this._gitFetch;
}
/** Replace the fetch status; true when it differs from the previous one. */
setGitFetchStatus(status: GitFetchStatus): boolean {
const changed = JSON.stringify(status) !== JSON.stringify(this._gitFetch);
this._gitFetch = status;
return changed;
}
/**
* True while the running turn is Codeman's own keep-alive nudge: its stop hook and idle
* prompt open pre-acknowledged, and its submit moves `lastSubmitAt` (it IS a submit, and the
@@ -2116,6 +2162,9 @@ export class Session extends EventEmitter {
statusLineExporter: this.statusLineExporter,
keepWarmEnabled: this._keepWarmEnabled,
keepWarm: this._keepWarm ?? undefined,
gitFetchEnabled: this._gitFetchEnabled,
gitFetchIntervalSeconds: this._gitFetchIntervalSeconds,
gitFetch: this._gitFetch ?? undefined,
imageWatcherEnabled: this._imageWatcherEnabled,
pinned: this._pinned || undefined,
pinnedAt: this._pinned ? (this._pinnedAt ?? undefined) : undefined,
+15
View File
@@ -33,6 +33,7 @@
import type { RespawnConfig } from './respawn.js';
import type { AttachmentDetectedType } from './tools.js';
import type { GitFetchStatus } from '../git-fetch.js';
/** Status of a Claude session */
export type SessionStatus = 'idle' | 'busy' | 'stopped' | 'error';
@@ -891,6 +892,20 @@ export interface SessionState {
keepWarmEnabled?: boolean;
/** What the keep-warm is doing right now; ephemeral, never restored. */
keepWarm?: KeepWarmStatus;
/**
* Git fetch on an interval for this session's repositories; absent = follow the app-wide
* `gitFetchEnabled` default. Restored on a restart, like `keepWarmEnabled`, because the choice is the
* user's and outlives the run.
*/
gitFetchEnabled?: boolean;
/** Seconds between this session's runs; absent = follow the app-wide `gitFetchIntervalSeconds` default. */
gitFetchIntervalSeconds?: number;
/**
* What this session's last fetch did. Written to disk with the rest of the record, but the restore copies
* only the fields its own config lists and this is not one of them, so it is the panel's truth for the
* life of the session, not across a restart.
*/
gitFetch?: GitFetchStatus;
/** Pinned to the top of the session manager list (COD-139) */
pinned?: boolean;
/** When the session was pinned (epoch ms) — orders the pinned group, most-recent-first */
+4
View File
@@ -2455,6 +2455,10 @@ class CodemanApp {
// Update parentSessionName for any subagents belonging to this session
// (fixes stale name display after session rename)
this.updateSubagentParentNames(session.id);
// A scheduled fetch publishes the session's result on this same event, so an open Session Options modal
// on that session shows it without polling its own (session-ui.js: updateGitFetchStatus, which leaves the
// control being typed in alone).
if (this.editingSessionId === session.id) this.updateGitFetchStatus(session.id);
// If claudeSessionId was just set, re-check orphan subagents
// This connects subagents that were waiting for the session to identify itself
if (claudeSessionIdJustSet) {
+88 -5
View File
@@ -9,9 +9,13 @@
* OPTIONAL and per-device: `showGitStatus` (App Settings → Header & Panels → Bottom bar), default
* OFF. While it is off nothing polls and the button never shows. While it is on, the page asks
* `GET /api/sessions/:id/git-status` for the active session on a slow poll (and at once when the
* session changes or the window regains focus). The route is read-only and offline: it never fetches
* or changes the repository, so the "behind" number reflects the last `git fetch`, which the panel
* footer says. Remote (SSH) and Docker sessions answer `unsupported` and show no indicator.
* session changes or the window regains focus). The status route is read-only: it never changes the
* repository, so the "behind" number reflects the last `git fetch`, which the panel footer says. Fetching
* happens when the user clicks Fetch in that window's header (`POST /api/sessions/:id/git-fetch`,
* src/git-fetch.ts), or on the interval when the session is on: this is the only git command the Git panel
* runs that writes, and the only one Codeman runs on a timer — cloning and worktree management write too,
* but only when the user asked for them at that moment. Remote (SSH)
* and Docker sessions answer `unsupported`, show no indicator, and cannot be fetched.
*
* Everything that comes from git (file names, commit subjects, author names) is untrusted text: it is
* only ever written with `textContent`, never `innerHTML`.
@@ -265,6 +269,78 @@ Object.assign(CodemanApp.prototype, {
return this.refreshGitStatus({ fresh: true });
},
/**
* Fetch, on this click only: one `git fetch --quiet` per repository the panel shows
* (`POST /api/sessions/:id/git-fetch`). It is the only git command the Git panel runs that writes, and the
* only one Codeman runs on a timer, and it updates remote-tracking refs only: nothing here commits or
* touches the working tree, so an agent's own work is left alone — though a fetch does hold git's ref lock,
* so an agent's `git pull` in the same repository can hit the same `cannot lock ref` while it runs. One
* click means one fetch per repository: the button is busy and a second click is ignored while it runs, and
* a click that joins a fetch already running reports that run, not itself. The panel then re-reads, so the
* "behind" number reflects what this fetch brought.
*/
async fetchGitStatusNow() {
const sid = this.activeSessionId || null;
const btn = this.$('gitStatusFetchBtn');
if (!sid || !btn || this._gitFetchInFlight) return;
this._gitFetchInFlight = true;
this._renderGitFetchButton();
let report = null;
try {
const query = new URLSearchParams(this.gitStatusLimits());
report = await this._apiJson(`/api/sessions/${encodeURIComponent(sid)}/git-fetch?${query}`, { method: 'POST' });
} catch {
report = null;
}
// A fetch that lands after a session switch is not shown for the session on screen now; the refs it
// moved are still on disk, so that session's own read reflects them.
if (sid === this.activeSessionId) this._gitStatusFetch = report ? { sessionId: sid, data: report } : null;
this._gitFetchInFlight = false;
await this.refreshGitStatus({ fresh: true });
},
/** The last Fetch this window ran for the session on screen, or null. */
_currentGitFetch() {
const f = this._gitStatusFetch;
return f && f.sessionId === this.activeSessionId && f.data ? f.data : null;
},
/** Busy while a fetch runs, and never enabled for a session there is nothing to fetch for. */
_renderGitFetchButton() {
const btn = this.$('gitStatusFetchBtn');
if (!btn) return;
const overview = this._currentGitStatus();
const fetchable = !!this.activeSessionId && !!overview && overview.state === 'ok';
btn.disabled = this._gitFetchInFlight || !fetchable;
if (this._gitFetchInFlight) btn.setAttribute('aria-busy', 'true');
else btn.removeAttribute('aria-busy');
},
/** What the last Fetch brought: a summary line, then one row per repository it could not fetch. */
_gitFetchNote() {
const report = this._currentGitFetch();
if (!report || report.state !== 'ok' || !report.repos?.length) return null;
const el = (tag, cls, text) => this._gitEl(tag, cls, text);
const failed = report.repos.filter((r) => !r.ok);
const count = report.repos.length;
const note = el('div', 'git-status-fetch-note');
note.append(
el(
'div',
'git-status-fetch-summary',
`Fetched ${new Date(report.fetchedAt).toLocaleTimeString()}: ${count - failed.length} of ${count} ${count === 1 ? 'repository' : 'repositories'}.`
)
);
for (const r of failed) {
const row = el('div', 'git-status-fetch-row');
row.append(el('span', 'git-status-repo-name', r.name));
if (r.path !== r.name) row.append(el('span', 'git-status-repo-path', r.path));
row.append(el('span', 'git-status-repo-unreadable', `⚠ ${r.failure?.message || 'git fetch failed'}`));
note.append(row);
}
return note;
},
/** Drag by the header. Pointer events cover mouse, pen and touch; one set of listeners lives as long as the page. */
_ensureGitStatusPanelDrag() {
const panel = this.$('gitStatusPanel');
@@ -313,6 +389,7 @@ Object.assign(CodemanApp.prototype, {
if (!body) return;
const overview = this._currentGitStatus();
const el = (tag, cls, text) => this._gitEl(tag, cls, text);
this._renderGitFetchButton();
// The 15 s poll replaces every row: put keyboard focus back on the same file afterwards.
const focusKey = body.contains(document.activeElement)
? document.activeElement.closest?.('[data-git-key]')?.dataset.gitKey
@@ -379,8 +456,13 @@ Object.assign(CodemanApp.prototype, {
}
}
const note = this._gitFetchNote();
if (note) body.append(note);
if (foot) {
foot.textContent = `Checked ${new Date(overview.checkedAt).toLocaleTimeString()}. Read-only: Codeman never fetches or changes the repository, so “behind” is as of your last fetch.`;
// Runtime text (the panel footer carries data-i18n-skip), so naming the interval here does not fight the
// translator. It says what actually runs: this click, or the interval the user turned on.
foot.textContent = `Checked ${new Date(overview.checkedAt).toLocaleTimeString()}. Read-only apart from Fetch: Codeman fetches on your click, or on the interval you turned on in Settings, and never commits or changes the repository, so “behind” is as of the last fetch.`;
}
if (focusKey) {
const again = [...body.querySelectorAll('[data-git-key]')].find((n) => n.dataset.gitKey === focusKey);
@@ -449,7 +531,8 @@ Object.assign(CodemanApp.prototype, {
if (data.ahead) line.append(el('span', 'git-status-chip git-status-chip--warn', `↑ ${data.ahead} ahead`));
if (data.behind) {
const behind = el('span', 'git-status-chip', `↓ ${data.behind} behind`);
behind.title = 'As of the last git fetch: Codeman never fetches.';
behind.title =
'As of the last git fetch — click Fetch in this window, or turn on the fetch interval in Settings, to bring it current.';
line.append(behind);
}
} else if (data.hasRemote) {
+31 -4
View File
@@ -351,6 +351,7 @@
Delete: '删除',
Remove: '移除',
Edit: '编辑',
Fetch: '拉取',
Refresh: '刷新',
Back: '返回',
Next: '下一步',
@@ -519,12 +520,13 @@
'Connection tile: offline': '离线',
'Connection tile: queued': '已排队',
'Connection tile: retry': '重连中',
// App Settings → Bottom bar, translated as one group (the Git status rows,
// #543's two included). Keys are the trimmed label text, without the scope tag.
// App Settings → Bottom bar, translated as one group (the Git status rows, #543's two included, and the
// two Git fetch rows, in the order the page lists them). Keys are the trimmed label text, without the
// scope tag. The Session Options → Git strings are in that group's own block further down.
'Bottom bar': '底部栏',
'Git status': 'Git 状态',
"Shows, at the right of the bottom bar, when the active session's repository (or each repository inside its folder, up to two levels down) has uncommitted files or commits that are not pushed. Click it for the list. Read-only: Codeman never fetches or changes the repository. Not shown for Docker or remote sessions. Off by default.":
'在底部栏右侧显示当前会话的仓库(或其文件夹内向下两层以内的每个仓库)是否有未提交的文件或未推送的提交。点击可查看列表。只读:{name} 从不拉取或更改仓库。Docker 和远程会话不显示。默认关闭。',
"Shows, at the right of the bottom bar, when the active session's repository (or each repository inside its folder, up to two levels down) has uncommitted files or commits that are not pushed. Click it for the list. Read-only apart from Fetch: Codeman never commits or changes the repository, and `git fetch` — the only git command the Git window runs that writes, and the only one Codeman runs on a timer (cloning and worktree management write too, but only when you asked for them at the moment you asked) — runs when you click Fetch in that window, or on the interval below if you turned it on. Not shown for Docker or remote sessions. Off by default.":
'在底部栏右侧显示当前会话的仓库(或其文件夹内向下两层以内的每个仓库)是否有未提交的文件或未推送的提交。点击可查看列表。除拉取外只读:{name} 从不提交或更改仓库,而拉取是 Git 窗口运行的唯一会写入的 git 命令,也是 {name} 唯一会按间隔自行运行的命令(克隆和工作树管理也会写入,但只在您当时要求时才运行),它只在您点击该窗口中的拉取按钮时运行,或在您开启了下方的定时后按间隔运行。Docker 和远程会话不显示。默认关闭。',
'Git status: group files by folder': 'Git 状态:按文件夹分组显示文件',
'In the Git window, show changed files under their folders, collapsed until you click a folder. Off lists every file by its full path. On by default.':
'在 Git 窗口中,将更改的文件显示在各自的文件夹下,点击文件夹前保持折叠。关闭时按完整路径列出每个文件。默认开启。',
@@ -534,6 +536,13 @@
'Git status: git timeout': 'Git 状态:git 超时',
'Seconds one git command may run before that repository is reported as unreadable (5 to 120, default 30). Raise it for repositories on a slow network share.':
'单条 git 命令可运行的秒数,超时后该仓库会被报告为无法读取(5 到 120,默认 30)。仓库位于较慢的网络共享上时请调高此值。',
'Git fetch on an interval': 'Git 定时拉取',
'Runs `git fetch` for the repositories the Git window lists on a timer, so the "behind" number is current without a click. Off by default: this is the only git command the Git panel runs that writes, and the only one Codeman runs on a timer (cloning and worktree management write too, but only when you asked for them at the moment you asked), so nothing runs until you turn it on. A session can override both the switch and the interval in Session Options → Git.':
'按间隔为 Git 窗口列出的仓库运行拉取,这样“落后”的数字无需点击就是最新的。默认关闭:这是 Git 窗口运行的唯一会写入的 git 命令,也是 {name} 唯一会按间隔自行运行的命令(克隆和工作树管理也会写入,但只在您当时要求时才运行),所以在您开启之前不会有任何运行。会话可以在“会话选项 → Git”中同时覆盖开关和间隔。',
'Git fetch: how often': 'Git 定时拉取:多久一次',
'Seconds between runs for a session that has no override of its own (30 to 3600, default 300). Only a session that is on — here, or in Session Options → Git — is fetched, and sessions sharing one folder are fetched by one run.':
'没有自己覆盖设置的会话,两次运行之间的秒数(30 到 3600,默认 300)。只有已开启的会话——这里,或在“会话选项 → Git”——才会被拉取,共用一个文件夹的会话由一次运行拉取。',
'Fetch git status': '拉取 Git 状态',
'Refresh git status': '刷新 Git 状态',
'Close git status': '关闭 Git 状态',
Panels: '面板',
@@ -832,6 +841,24 @@
Memory: '内存',
GPUs: 'GPU',
// Session Options → Git (the tab's blurb, its group head, its hint and its three rows in index.html, plus
// the save toast session-ui.js raises). 'Status' is not a key here: that row's text is built at runtime
// by updateGitFetchStatus, and 'Git' stays a technical name.
"Whether Codeman fetches this session's repositories on a timer.": '{name} 是否按间隔拉取此会话的仓库。',
'Fetch on an interval': '按间隔拉取',
"Fetching is the only git command the Git panel runs that writes, and the only one Codeman runs on a timer, so nothing runs until you turn it on — here, or in App Settings → Bottom bar. Cloning and worktree management write too, but only when you asked for them at the moment you asked. The panel's Fetch button is always just a click.":
'拉取是 Git 窗口运行的唯一会写入的 git 命令,也是 {name} 唯一会按间隔自行运行的命令,所以在您开启之前(这里,或“应用设置 → 底部栏”)不会有任何运行。克隆和工作树管理也会写入,但只在您当时要求时才运行。该窗口中的拉取按钮始终只是一次点击。',
'Follow the app setting': '跟随应用设置',
'Uses the app-wide switch and interval for this session. Switch it off to pick your own.':
'为此会话使用应用级的开关和间隔。关闭它即可自行选择。',
'Fetch this session': '拉取此会话',
"Runs on its own even while the app-wide switch is off: a session that turned itself on means exactly that. Sessions sharing one folder share one run, and each sees that run's result.":
'即使应用级开关关闭也自行运行:一个自己开启的会话正是这个意思。共用一个文件夹的会话共享一次运行,每个会话都会看到该运行的结果。',
'How often': '多久一次',
'30 sec to 1 hr, timed from the start of a run, so a slow repository does not push the next one out.':
'30 秒到 1 小时,从一次运行的开始计时,所以较慢的仓库不会把下一次推远。',
'Git fetch settings saved': 'Git 定时拉取设置已保存',
// Cron / lifecycle / panels
'Cron Jobs': '定时任务',
'+ New Job': '+ 新建任务',
+71 -1
View File
@@ -625,6 +625,7 @@
<span class="git-status-title">Git <span class="git-status-branch" id="gitStatusBranch" data-i18n-skip></span></span>
<div class="git-status-actions">
<button class="btn-icon-sm" onclick="app.refreshGitStatusNow()" title="Refresh" aria-label="Refresh git status">&#x21BB;</button>
<button class="btn-icon-sm" id="gitStatusFetchBtn" onclick="app.fetchGitStatusNow()" title="Fetch" aria-label="Fetch git status">&#x2913;</button>
<button class="btn-icon-sm" onclick="app.closeGitStatusPanel()" title="Close" aria-label="Close git status">&times;</button>
</div>
</div>
@@ -1331,6 +1332,13 @@
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 3v18h18"/><polyline points="7 14 11 10 14 13 20 7"/></svg>
<span>Summary</span>
</button>
<!-- Git is last: the section shows for every local session, but until the interval feature is
in use it holds one toggle and a status row that has never run, so it earns its place at the
end of the rail rather than among the tabs a session uses every day. -->
<button type="button" class="set-rail-item" data-tab="git" onclick="app.switchOptionsTab('git')">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="18" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><path d="M6 3v12"/><path d="M18 9a9 9 0 0 1-9 9"/></svg>
<span>Git</span>
</button>
</div>
<p class="set-rail-foot">These options belong to the selected session and save as you change them.</p>
</nav>
@@ -1719,6 +1727,54 @@
</div>
</div>
</section>
<!-- ══ Git ══════════════════════════════════════════════════════ -->
<section class="set-section hidden" id="git-tab" data-label="Git">
<div class="set-section-head">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="18" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><path d="M6 3v12"/><path d="M18 9a9 9 0 0 1-9 9"/></svg>
<h2>Git</h2>
</div>
<p class="set-section-blurb">Whether Codeman fetches this session's repositories on a timer.</p>
<div class="set-group">
<div class="set-group-head"><h4>Fetch on an interval</h4></div>
<p class="set-group-hint">Fetching is the only git command the Git panel runs that writes, and the only one Codeman runs on a timer, so nothing runs until you turn it on &mdash; here, or in App Settings &rarr; Bottom bar. Cloning and worktree management write too, but only when you asked for them at the moment you asked. The panel's Fetch button is always just a click.</p>
<div class="set-group-body">
<!-- Live from the session's own last run (session-ui.js: updateGitFetchStatus), which is the
run its folder got: several sessions on one folder share one run and read the same row. -->
<div class="set-row">
<div class="set-row-text">
<span class="set-row-label">Status</span>
<span class="set-row-desc" id="gitFetchStatus" data-i18n-skip hidden></span>
</div>
</div>
<div class="set-row">
<div class="set-row-text">
<span class="set-row-label">Follow the app setting</span>
<span class="set-row-desc">Uses the app-wide switch and interval for this session. Switch it off to pick your own.</span>
</div>
<label class="switch switch-sm"><input type="checkbox" id="modalGitFetchFollow" checked onchange="app.autoSaveGitFetch()"><span class="slider"></span></label>
</div>
<div class="set-row" id="gitFetchEnabledRow">
<div class="set-row-text">
<span class="set-row-label">Fetch this session</span>
<span class="set-row-desc">Runs on its own even while the app-wide switch is off: a session that turned itself on means exactly that. Sessions sharing one folder share one run, and each sees that run's result.</span>
</div>
<label class="switch switch-sm"><input type="checkbox" id="modalGitFetchEnabled" onchange="app.autoSaveGitFetch()"><span class="slider"></span></label>
</div>
<div class="set-row" id="gitFetchIntervalRow">
<div class="set-row-text">
<span class="set-row-label">How often</span>
<span class="set-row-desc">30 sec to 1 hr, timed from the start of a run, so a slow repository does not push the next one out.</span>
</div>
<div class="set-row-actions">
<input type="number" id="modalGitFetchInterval" class="set-num set-num-wide" value="300" min="30" max="3600" step="30" onchange="app.autoSaveGitFetch()">
<span class="set-unit">sec</span>
</div>
</div>
</div>
</div>
</section>
</div>
</div>
</div>
@@ -2196,7 +2252,7 @@
<div class="set-row" data-search="git status uncommitted unpushed commit push indicator bottom bar toolbar">
<div class="set-row-text">
<span class="set-row-label">Git status <span class="set-scope">device</span></span>
<span class="set-row-desc">Shows, at the right of the bottom bar, when the active session's repository (or each repository inside its folder, up to two levels down) has uncommitted files or commits that are not pushed. Click it for the list. Read-only: Codeman never fetches or changes the repository. Not shown for Docker or remote sessions. Off by default.</span>
<span class="set-row-desc">Shows, at the right of the bottom bar, when the active session's repository (or each repository inside its folder, up to two levels down) has uncommitted files or commits that are not pushed. Click it for the list. Read-only apart from Fetch: Codeman never commits or changes the repository, and `git fetch` — the only git command the Git window runs that writes, and the only one Codeman runs on a timer (cloning and worktree management write too, but only when you asked for them at the moment you asked) — runs when you click Fetch in that window, or on the interval below if you turned it on. Not shown for Docker or remote sessions. Off by default.</span>
</div>
<label class="switch switch-sm"><input type="checkbox" id="appSettingsShowGitStatus"><span class="slider"></span></label>
</div>
@@ -2221,6 +2277,20 @@
</div>
<input type="number" id="appSettingsGitStatusTimeout" class="set-num" value="30" min="5" max="120" step="1">
</div>
<div class="set-row" data-search="git fetch interval timer behind remote tracking refs poll run automatically">
<div class="set-row-text">
<span class="set-row-label">Git fetch on an interval <span class="set-scope">synced</span></span>
<span class="set-row-desc">Runs `git fetch` for the repositories the Git window lists on a timer, so the "behind" number is current without a click. Off by default: this is the only git command the Git panel runs that writes, and the only one Codeman runs on a timer (cloning and worktree management write too, but only when you asked for them at the moment you asked), so nothing runs until you turn it on. A session can override both the switch and the interval in Session Options → Git.</span>
</div>
<label class="switch switch-sm"><input type="checkbox" id="appSettingsGitFetchEnabled"><span class="slider"></span></label>
</div>
<div class="set-row" data-search="git fetch how often seconds between runs interval case override session options">
<div class="set-row-text">
<span class="set-row-label">Git fetch: how often <span class="set-scope">synced</span></span>
<span class="set-row-desc">Seconds between runs for a session that has no override of its own (30 to 3600, default 300). Only a session that is on — here, or in Session Options → Git — is fetched, and sessions sharing one folder are fetched by one run.</span>
</div>
<input type="number" id="appSettingsGitFetchIntervalSeconds" class="set-num" value="300" min="30" max="3600" step="1">
</div>
</div>
</div>
+105
View File
@@ -2685,6 +2685,9 @@ Object.assign(CodemanApp.prototype, {
document.getElementById('modalKeepWarmEnabled').checked =
session.keepWarm?.enabled ?? session.keepWarmEnabled ?? false;
this.updateKeepWarmStatus(sessionId);
// Git: the session's own choice if it has one, otherwise the app setting. updateGitFetchStatus is also
// what SSE calls when a scheduled run lands, so the rows stay current while the modal is open.
this.updateGitFetchStatus(sessionId);
document.getElementById('modalImageWatcherEnabled').checked = session.imageWatcherEnabled ?? true;
document.getElementById('modalFlickerFilterEnabled').checked = session.flickerFilterEnabled ?? false;
@@ -2741,6 +2744,12 @@ Object.assign(CodemanApp.prototype, {
if (respawnTabBtn) respawnTabBtn.style.display = '';
}
// Git is local git only: a remote (SSH) or Docker case answers 'unsupported' on both git routes and is
// never fetched by the interval scheduler, so its Git tab has nothing to say and its rail entry goes
// hidden the same way.
const gitTabBtn = document.querySelector('#sessionOptionsModal .set-rail-item[data-tab="git"]');
if (gitTabBtn) gitTabBtn.style.display = session.remote || session.docker ? 'none' : '';
// Populate Ralph Wiggum form with current session values (skip for external CLI sessions)
if (!isExternalCli) {
const ralphState = this.ralphStates.get(sessionId);
@@ -3022,6 +3031,101 @@ Object.assign(CodemanApp.prototype, {
}
},
/**
* The Git tab: the session's last scheduled run, and which values its rows show. A session with no choice of
* its own follows the app setting, so its switch and interval display the app's numbers and go inert (the
* same inert-row pattern as updateKeepWarmStatus above), because changing them here is what makes the session
* stop following. The app numbers come from the settings cache, so what this shows can be one settings load
* behind; the server decides from a fresh read, not from what the page displays.
*
* SSE calls this on every `session:updated` for the open session (app.js `_onSessionUpdated`), and a working
* session sends one on each working/idle change, so a control the user is in (`document.activeElement`) is
* left as it is: rewriting it put a half-typed interval back to the stored one before `onchange` could save it.
*/
updateGitFetchStatus(sessionId) {
const statusEl = document.getElementById('gitFetchStatus');
const followBox = document.getElementById('modalGitFetchFollow');
const box = document.getElementById('modalGitFetchEnabled');
const num = document.getElementById('modalGitFetchInterval');
if (!statusEl || !followBox || !box || !num || this.editingSessionId !== sessionId) return;
const session = this.sessions.get(sessionId);
if (!session) return;
const app = this.loadAppSettingsFromStorage() || {};
// No choice of its own on either field means the session follows the app. A partial one (its own switch,
// the app's interval) means it does not, and the row that still follows shows the app's value, which is
// also the value the scheduler runs it with (a default here would show one number and fetch at another).
const follows = session.gitFetchEnabled === undefined && session.gitFetchIntervalSeconds === undefined;
const enabled = session.gitFetchEnabled ?? (app.gitFetchEnabled === true);
const interval = session.gitFetchIntervalSeconds ?? app.gitFetchIntervalSeconds ?? 300;
const focused = document.activeElement;
if (followBox !== focused) followBox.checked = follows;
if (box !== focused) box.checked = enabled;
if (num !== focused) num.value = interval;
for (const el of [box, num]) {
el.closest('.set-row')?.classList.toggle('set-row-disabled', follows);
el.disabled = follows;
}
const run = session.gitFetch;
const parts = run
? [
`Last run ${this._gitFetchAgo(run.ranAt)}${run.trigger === 'interval' ? ' on the interval' : ' by click'}`,
run.state === 'ok' ? `${run.repos} repositories` : run.state,
run.failed ? `${run.failed} failed` : '',
]
: [follows ? 'Nothing fetched on a timer yet, and this session follows the app setting.' : 'Nothing fetched on a timer yet for this session.'];
statusEl.textContent = parts.filter(Boolean).join(' · ');
statusEl.hidden = false;
},
/** 'just now', '4m', '2h' — the short stamps the tab rows use, measured from a run's start. */
_gitFetchAgo(ts) {
const seconds = Math.max(0, Math.round((Date.now() - ts) / 1000));
if (seconds < 60) return seconds < 10 ? 'just now' : `${seconds}s`;
if (seconds < 3600) return `${Math.round(seconds / 60)}m`;
return `${Math.round(seconds / 3600)}h`;
},
async autoSaveGitFetch() {
if (!this.editingSessionId) return;
const follow = document.getElementById('modalGitFetchFollow').checked;
const num = document.getElementById('modalGitFetchInterval');
// `null` on the route means "no choice of your own", which is what following the app setting is.
const body = follow
? { enabled: null, intervalSeconds: null }
: {
enabled: document.getElementById('modalGitFetchEnabled').checked,
intervalSeconds: Math.min(3600, Math.max(30, parseInt(num.value, 10) || 300)),
};
// Enter fires `onchange` with the field still focused, and updateGitFetchStatus leaves a focused field
// alone, so the clamped number is written back here or the field would keep showing what was typed.
if (!follow) num.value = body.intervalSeconds;
try {
// `_apiPost` hands back the Response without checking it, so a refused body (a 400) still read as a
// save. `_apiJson` is the one that says whether the call went through, and null here means it did not.
const data = await this._apiJson(`/api/sessions/${this.editingSessionId}/git-fetch-settings`, {
method: 'POST',
body,
});
if (!data) {
this.showToast('Failed to save Git fetch settings', 'error');
return;
}
const session = this.sessions.get(this.editingSessionId);
const saved = data.gitFetchSettings;
if (session && saved) {
session.gitFetchEnabled = saved.enabled ?? undefined;
session.gitFetchIntervalSeconds = saved.intervalSeconds ?? undefined;
}
this.updateGitFetchStatus(this.editingSessionId);
this.showToast('Git fetch settings saved', 'success');
} catch (err) {
this.showToast('Failed to save Git fetch settings: ' + err.message, 'error');
}
},
async toggleSessionImageWatcher() {
if (!this.editingSessionId) return;
const enabled = document.getElementById('modalImageWatcherEnabled').checked;
@@ -3160,6 +3264,7 @@ Object.assign(CodemanApp.prototype, {
document.getElementById('context-tab').classList.toggle('hidden', tabName !== 'context');
document.getElementById('ralph-tab').classList.toggle('hidden', tabName !== 'ralph');
document.getElementById('summary-tab').classList.toggle('hidden', tabName !== 'summary');
document.getElementById('git-tab').classList.toggle('hidden', tabName !== 'git');
// A switched-to section starts at its own top, not at the scroll offset the
// previous one was left at.
+12
View File
@@ -602,6 +602,11 @@ Object.assign(CodemanApp.prototype, {
document.getElementById('appSettingsGitStatusTree').checked = settings.gitStatusTree ?? defaults.gitStatusTree ?? true;
document.getElementById('appSettingsGitStatusMaxRepos').value = settings.gitStatusMaxRepos ?? defaults.gitStatusMaxRepos ?? 12;
document.getElementById('appSettingsGitStatusTimeout').value = settings.gitStatusTimeoutSeconds ?? defaults.gitStatusTimeoutSeconds ?? 30;
// Git fetch on an interval: synced, default OFF, interval default 300 s (DEFAULT_GIT_FETCH_INTERVAL_SECONDS).
// Synced means the SERVER decides whether to fetch, so these keys stay out of the per-device display list
// below and are not stripped from a save — a stripped key would never reach the scheduler.
document.getElementById('appSettingsGitFetchEnabled').checked = settings.gitFetchEnabled === true;
document.getElementById('appSettingsGitFetchIntervalSeconds').value = settings.gitFetchIntervalSeconds ?? 300;
// Gesture control lives in the Input section (alongside Local Echo / CJK Input)
// but is only available when the instance runs with CODEMAN_GESTURE=1 (server sets
// window.__codemanGestureAvailable). Hide just this item otherwise so the toggle
@@ -3008,6 +3013,13 @@ Object.assign(CodemanApp.prototype, {
// Clamped here and again on the server; an empty or odd value falls back to the default.
gitStatusMaxRepos: Math.min(50, Math.max(1, parseInt(document.getElementById('appSettingsGitStatusMaxRepos').value, 10) || 12)),
gitStatusTimeoutSeconds: Math.min(120, Math.max(5, parseInt(document.getElementById('appSettingsGitStatusTimeout').value, 10) || 30)),
// Clamped to the schema's bounds here too: a value outside them fails the whole save, and these keys
// must survive the strip below because the server's scheduler is what reads them.
gitFetchEnabled: document.getElementById('appSettingsGitFetchEnabled').checked,
gitFetchIntervalSeconds: Math.min(
3600,
Math.max(30, parseInt(document.getElementById('appSettingsGitFetchIntervalSeconds').value, 10) || 300)
),
gestureControlEnabled: document.getElementById('appSettingsGestureControl').checked,
subagentTrackingEnabled: document.getElementById('appSettingsSubagentTracking').checked,
subagentActiveTabOnly: document.getElementById('appSettingsSubagentActiveTabOnly').checked,
+56 -1
View File
@@ -22148,6 +22148,42 @@ html .toolbar .btn-git-status[aria-expanded='true'] {
gap: 0.25rem;
}
/* A Fetch button cannot be clicked twice while its fetch is running, and is not offered for a session
there is nothing to fetch for (no repository, remote or Docker). Scoped to the Git panel's header: the
File Viewer's Back/Forward and the folder grid's Up button are .btn-icon-sm too, and keep their own look. */
.git-status-actions .btn-icon-sm[disabled] {
color: var(--text-dim);
opacity: 0.45;
cursor: default;
}
.git-status-actions .btn-icon-sm[disabled]:hover {
background: none;
}
.git-status-actions .btn-icon-sm[aria-busy='true'] {
color: var(--text);
animation: btn-icon-busy 1.1s ease-in-out infinite;
}
@keyframes btn-icon-busy {
0%,
100% {
opacity: 0.55;
}
50% {
opacity: 0.9;
}
}
/* No pulse under reduced motion: the button holds the pulse's brighter step, still dimmer than at rest. */
@media (prefers-reduced-motion: reduce) {
.git-status-actions .btn-icon-sm[aria-busy='true'] {
animation: none;
opacity: 0.7;
}
}
.git-status-body {
flex: 1;
overflow-y: auto;
@@ -22167,7 +22203,8 @@ html .toolbar .btn-git-status[aria-expanded='true'] {
.git-status-empty,
.git-status-ok,
.git-status-note,
.git-status-more {
.git-status-more,
.git-status-fetch-note {
color: var(--text-muted);
padding: 0.25rem 0;
}
@@ -22176,6 +22213,24 @@ html .toolbar .btn-git-status[aria-expanded='true'] {
color: rgb(34, 197, 94);
}
/* The last Fetch's result: a summary line, then a row per repository it could not fetch. */
.git-status-fetch-note {
margin-top: 0.6rem;
padding-top: 0.4rem;
border-top: 1px solid var(--border);
}
.git-status-fetch-summary {
margin-bottom: 0.2rem;
}
.git-status-fetch-row {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
padding: 0.1rem 0;
}
.git-status-branchline {
display: flex;
flex-wrap: wrap;
+55 -10
View File
@@ -1,21 +1,25 @@
/**
* @fileoverview `GET /api/sessions/:id/git-status`: what the session's workspace has not committed or
* pushed (src/git-workspace-status.ts), for the bottom-bar Git indicator and its panel. The answer is
* @fileoverview The Git panel's routes: `GET /api/sessions/:id/git-status` (what the session's workspace
* has not committed or pushed, src/git-workspace-status.ts) and `POST /api/sessions/:id/git-fetch` (the
* panel's Fetch button, src/git-fetch.ts), for the bottom-bar Git indicator and its window. The answer is
* an overview: the enclosing repository, or each repository found below a folder that holds several
* projects (see `getGitWorkspaceOverview` for exactly which).
*
* Read-only and offline: it never fetches and never runs a git write command. A remote (SSH) or
* Docker session is not inspected and answers `state: 'unsupported'`, and neither is any repository at or
* inside a Docker case workspace (a container can write there, and git here would run on the host). Ownership goes through
* Read-only and offline: the status route never fetches and never runs a git write command. Fetching is a
* separate, user-triggered path (`POST /api/sessions/:id/git-fetch`, src/git-fetch.ts) that the panel calls
* only when the user clicks Fetch. A remote (SSH) or Docker session is not inspected and answers
* `state: 'unsupported'` on both routes, and neither is any repository at or inside a Docker case
* workspace (a container can write there, and git here would run on the host). Ownership goes through
* `findSessionOrFail`, like every session-scoped route.
*/
import type { FastifyInstance } from 'fastify';
import { ApiErrorCode, createErrorResponse, getErrorMessage, type ApiResponse } from '../../types.js';
import { redactGitCredentials } from '../../git-clone.js';
import { emptyReport, fetchWorkspaceOnce, gitFetchStatusFrom, type GitFetchReport } from '../../git-fetch.js';
import { readDockerCases } from '../../docker-hosts.js';
import { getDataDir } from '../../config/instance.js';
import { findSessionOrFail } from '../route-helpers.js';
import { findSessionOrFail, persistAndBroadcastSession } from '../route-helpers.js';
import {
emptyOverview,
findWorkspaceRepo,
@@ -28,10 +32,14 @@ import {
type GitRunner,
type GitWorkspaceOverview,
} from '../../git-workspace-status.js';
import type { SessionPort } from '../ports/index.js';
import type { EventPort, SessionPort } from '../ports/index.js';
/** Host paths of every Docker case workspace: repositories at or inside these are never inspected. */
const defaultDockerWorkspaces = async (): Promise<string[]> =>
/**
* Host paths of every Docker case workspace: repositories at or inside these are never inspected.
* Exported so the interval scheduler (src/git-fetch-scheduler.ts) uses the SAME list — the Docker rule has
* to be one rule, checked by every path that could run git.
*/
export const defaultDockerWorkspaces = async (): Promise<string[]> =>
(await readDockerCases(getDataDir()).catch(() => [])).map((c) => c.hostWorkspacePath).filter(Boolean);
/**
@@ -50,7 +58,9 @@ function limitsFrom(query: { maxRepos?: unknown; timeout?: unknown }) {
export function registerGitStatusRoutes(
app: FastifyInstance,
ctx: SessionPort,
// EventPort as well as SessionPort: the fetch route publishes the run it did, and a route that broadcasts
// has to say so in its own signature.
ctx: SessionPort & EventPort,
git?: GitRunner,
dockerWorkspaces: () => Promise<string[]> = defaultDockerWorkspaces
): void {
@@ -119,4 +129,39 @@ export function registerGitStatusRoutes(
);
}
});
// Fetch, and only because the user clicked Fetch in the panel (src/git-fetch.ts): one
// `git fetch --quiet` per repository the panel would show, through the same resolver so the two cannot
// disagree about which repositories belong to the workspace. This is the only git command the Git panel runs
// that writes, and it writes remote-tracking refs only — nothing commits, checks out or merges. Cloning and
// worktree management write too, but those happen when the user asked for them; this route is the one that
// can also run later, on a timer. It is not as harmless as a read though: a fetch holds git's ref lock, so
// an agent's own `git pull` in the same clone can collide with it, which is why the run goes through
// `fetchWorkspaceOnce` — a click while a tick is already fetching this folder joins that run instead of
// starting a second one. It can also run a
// repository's own hooks (`reference-transaction`, `pre-auto-gc` through the maintenance git runs after a
// fetch) and its config commands such as `credential.helper`, so the `FETCH_CONFIG_ARGS` overrides turn
// maintenance and gc off, and a repository a container can write to is refused before any git runs. Remote
// and Docker sessions answer `unsupported` like the status route.
app.post('/api/sessions/:id/git-fetch', async (req): Promise<ApiResponse<GitFetchReport>> => {
const { id } = req.params as { id: string };
const query = req.query as { maxRepos?: unknown; timeout?: unknown };
const limits = limitsFrom(query);
const session = findSessionOrFail(ctx, id, req);
if (session.remote) return { success: true, data: emptyReport('unsupported', { reason: 'remote' }) };
if (session.docker) return { success: true, data: emptyReport('unsupported', { reason: 'docker' }) };
const run = await fetchWorkspaceOnce(
session.workingDir,
{ git, ...limits, dockerWorkspaces: await dockerWorkspaces() },
'click'
);
// The response answers the click, and the run is also the session's current truth: what the panel's
// "behind" number is based on. Publishing it is what the api docs say a click does, and what makes a
// second tab open on the same folder see the same run. The trigger recorded is the RUN's, not this
// request's: a click that joined a tick already going fetched nothing itself, so the row has to name the
// interval as what fetched.
if (session.setGitFetchStatus(gitFetchStatusFrom(run.report, run.trigger)))
persistAndBroadcastSession(ctx, session);
return { success: true, data: run.report };
});
}
+35
View File
@@ -57,6 +57,7 @@ import {
AutoCompactSchema,
AutoResumeSchema,
KeepWarmSchema,
GitFetchSettingsSchema,
PinSessionSchema,
ImageWatcherSchema,
FlickerFilterSchema,
@@ -3608,6 +3609,40 @@ export function registerSessionRoutes(
};
});
// ========== Git fetch on an interval ==========
// Per-session override for the fetch interval (src/git-fetch-scheduler.ts), which is what the Session
// Options rows say it is: two sessions on one folder can hold different choices, and that folder is
// fetched when the first of them is due. `null` on either field clears this session's choice so the
// app-wide setting applies again, and a field left out of the body leaves the other half as it was: the
// Session Options rows save on their own. Refused for a remote or Docker session, exactly as the Git
// panel excludes them — a container can write to the repository it mounts, so git there would run that
// repository's own configuration on the host.
app.post('/api/sessions/:id/git-fetch-settings', async (req) => {
const { id } = req.params as { id: string };
const body = parseBody(GitFetchSettingsSchema, req.body, 'Invalid request body');
const session = findSessionOrFail(ctx, id, req);
if (session.remote || session.docker) {
return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Git fetch does not run for remote or Docker sessions');
}
const enabled = 'enabled' in body ? (body.enabled ?? undefined) : session.gitFetchEnabled;
const intervalSeconds =
'intervalSeconds' in body ? (body.intervalSeconds ?? undefined) : session.gitFetchIntervalSeconds;
session.setGitFetchSettings(enabled, intervalSeconds);
persistAndBroadcastSession(ctx, session);
return {
success: true,
data: {
gitFetchSettings: {
enabled: session.gitFetchEnabled ?? null,
intervalSeconds: session.gitFetchIntervalSeconds ?? null,
},
},
};
});
// ========== Auto-Resume (usage-limit pause) ==========
app.post('/api/sessions/:id/auto-resume', async (req) => {
+22
View File
@@ -1488,6 +1488,19 @@ export const SettingsUpdateSchema = z
promptCacheKeepWarm: z.boolean().optional(),
/** Hours after the last real prompt during which keep-alives are sent (default 2, DEFAULT_KEEP_WARM_MAX_HOURS). */
promptCacheKeepWarmMaxHours: z.number().min(0.5).max(24).optional(),
/**
* Git fetch on an interval (src/git-fetch-scheduler.ts): `git fetch` for the repositories the Git panel
* lists, run on a timer instead of only on the panel's Fetch click. SYNCED, default OFF, because the
* server is what runs it: `git fetch` is the only git command the Git panel runs that writes — cloning
* and worktree management write too, but only when the user asked for them at the moment they asked — and
* the only one that can run later by itself, on a timer, and the only one that can run a repository's own
* hooks (`reference-transaction`, `pre-auto-gc` through the automatic maintenance a fetch triggers, config
* commands such as `credential.helper`), so nothing runs on a timer until the user turns this on. Cap in seconds between runs (30 to 3600, default 300). A
* session can override both in Session Options → Git; `null` there clears the override, and sessions
* sharing one folder are fetched by one run.
*/
gitFetchEnabled: z.boolean().optional(),
gitFetchIntervalSeconds: z.number().int().min(30).max(3600).optional(),
/**
* Spawned tabs follow their parent: a session created by another one keeps
* following its parent's tab (into its group, moving with it) until moved by
@@ -1928,6 +1941,15 @@ export const AutoResumeSchema = z.object({
/** `POST /api/sessions/:id/keep-warm`: `null` clears the session's choice so the app-wide default applies. */
export const KeepWarmSchema = z.object({ enabled: z.boolean().nullable() });
/**
* `POST /api/sessions/:id/git-fetch-settings`: `null` clears the session's choice so the app-wide default
* applies. Both fields are optional, so a row that saves on its own does not clear the other.
*/
export const GitFetchSettingsSchema = z.object({
enabled: z.boolean().nullable().optional(),
intervalSeconds: z.number().int().min(30).max(3600).nullable().optional(),
});
/** POST /api/sessions/:id/pin (COD-139) — explicit pin state for idempotency. */
export const PinSessionSchema = z.object({
pinned: z.boolean(),
+65
View File
@@ -100,6 +100,7 @@ import { getLifecycleLog } from '../session-lifecycle-log.js';
import {
applyWorkspaceHooks,
pruneAgentSessionPreambles,
readGitFetchSettings,
readKeepWarmSettingsOrThrow,
readPlanUsageTelemetryEnabled,
removeAgentSessionPreamble,
@@ -123,6 +124,10 @@ import { AI_CHECK_MODEL } from '../config/ai-defaults.js';
import { approvalInbox } from './approval-inbox.js';
import { SCREEN_BLOCKED_SOURCE } from './screen-blocked.js';
import { PromptCacheKeepWarmService } from '../prompt-cache-keepwarm.js';
import { fetchWorkspaceOnce } from '../git-fetch.js';
import { GitFetchScheduler } from '../git-fetch-scheduler.js';
import { probePathKind } from '../utils/bounded-path-probe.js';
import { defaultDockerWorkspaces } from './routes/git-status-routes.js';
import { composerIsEmpty, plainFrame } from '../session-submit-verifier.js';
import { detectUsageLimitPause } from '../usage-limit-patterns.js';
import { stopDeepSeekWeb } from '../deepseek-web-server.js';
@@ -294,6 +299,7 @@ import {
STATS_COLLECTION_INTERVAL_MS,
INACTIVITY_TIMEOUT_MS,
CRON_TICK_INTERVAL,
GIT_FETCH_TICK_INTERVAL_MS,
} from '../config/server-timing.js';
/**
@@ -390,6 +396,36 @@ export class WebServer extends EventEmitter {
},
log: (message) => console.log(message),
});
// Git fetch on an interval (git-fetch-scheduler.ts): the due-tracking lives in the service; the server
// lends it the facts a decision needs and stores what it reports on the session. A field initializer for
// the same reason as the keep-warm one above, and the scheduler reads the app setting FRESH on every tick
// — that is what makes a live toggle take effect on the next tick, and what makes turning it off actually
// stop the fetching. Default OFF, so an install that never enabled it spawns nothing at all.
private readonly gitFetchScheduler = new GitFetchScheduler({
sessionIds: () => this.sessions.keys(),
getSession: (id) => this.sessions.get(id),
readSettings: readGitFetchSettings,
// The same Docker list the panel's routes use: the rule has to be one rule.
dockerWorkspaces: defaultDockerWorkspaces,
// Bounded probe, DEFAULT options (rule #516): a tick is a bulk scan, so it keeps the stall cap and must
// never be handed `pastCap`. A folder on a mount that stopped answering is skipped, not fetched.
probePath: (path) => probePathKind(path),
// Through the join, so the tick and the panel's Fetch button are the same run: a click on a folder the
// tick is already fetching joins it rather than starting a second `git fetch` in the same clone — and the
// run that gets published is the one that ran, with its own trigger.
fetch: (cwd, opts, trigger) => fetchWorkspaceOnce(cwd, opts, trigger),
publish: (id, status) => {
const session = this.sessions.get(id);
if (!session?.setGitFetchStatus(status)) return;
// No new SSE event: the status rides the session state the page already listens for, and the Git
// panel polls on its own clock. It is written to disk with the rest of the record, but the restore
// copies only the fields its own config lists and this is not one of them (src/types/session.ts), so
// what a run found is the panel's truth for the life of the session, not across a restart.
this.persistSessionState(session);
this.broadcast(SseEvent.SessionUpdated, this.getSessionStateWithRespawn(session));
},
log: (message) => console.log(message),
});
/**
* Wake-on-LAN registry, returned by `registerSessionRoutes`. Held for its LIFETIME
* only — `drop()` on session cleanup, `stop()` on shutdown. Waking from here would
@@ -1248,6 +1284,21 @@ export class WebServer extends EventEmitter {
registerRebootRestoreRoutes(this.app, ctx);
registerReadMyMindRoutes(this.app, ctx);
registerGitStatusRoutes(this.app, ctx);
// Git fetch on an interval: this is only the wake-up, the scheduler itself decides what is due. Off in
// tests for the same reason as the polls below — a test drives `tick()` directly instead of waiting on
// a timer the harness would have to keep alive. The setting is read FRESH inside `tick()`, so turning
// it on takes effect on the next tick and turning it off actually stops the fetching.
if (!this.testMode) {
this.cleanup.setInterval(
() => {
this.gitFetchScheduler.tick().catch((err) => {
console.error('[git fetch] interval tick failed:', getErrorMessage(err));
});
},
GIT_FETCH_TICK_INTERVAL_MS,
{ description: 'git fetch interval checker' }
);
}
registerStatusTelemetryRoutes(this.app, ctx);
registerSystemRoutes(this.app, ctx);
registerCaseRoutes(this.app, ctx);
@@ -1505,6 +1556,9 @@ export class WebServer extends EventEmitter {
): Promise<void> {
const session = this.sessions.get(sessionId);
this.keepWarmService.remove(sessionId);
// A closed session takes its place in the fetch schedule with it: otherwise a detached-and-forgotten id
// would still count as tracked, and its next run would land on a session that no longer exists.
this.gitFetchScheduler.remove(sessionId);
const pinned = session?.pinned === true || this.store.getSession(sessionId)?.pinned === true;
if (coordinateLayout && session && killMux && !pinned) {
return this.tabLayouts.runSessionDeletion([{ id: sessionId, owner: session.owner }], () =>
@@ -3542,6 +3596,9 @@ export class WebServer extends EventEmitter {
if (saved.autoClearEnabled !== undefined || saved.autoClearThreshold !== undefined) {
session.setAutoClear(saved.autoClearEnabled ?? false, saved.autoClearThreshold);
}
if (saved.gitFetchEnabled !== undefined || saved.gitFetchIntervalSeconds !== undefined) {
session.setGitFetchSettings(saved.gitFetchEnabled, saved.gitFetchIntervalSeconds);
}
if (saved.autoResumeEnabled) {
// The stamp is re-armed by default, because a Codeman restart leaves the
// limit footer un-reprinted and dropping it there would strand the pause.
@@ -3764,6 +3821,11 @@ export class WebServer extends EventEmitter {
// below, a future `expiresAt` re-arms the timer once the pane is attached.
lastRealPromptAt: savedState?.lastRealPromptAt,
keepWarmEnabled: savedState?.keepWarmEnabled,
// The session's own fetch switch and interval, carried over rather than reset to the app default:
// the choice is the user's and outlives the run that made it. The scheduler reads them fresh
// on its next tick, so a restored session is back on its own schedule without a restart.
gitFetchEnabled: savedState?.gitFetchEnabled,
gitFetchIntervalSeconds: savedState?.gitFetchIntervalSeconds,
// Conversations this pane provably owned, oldest first. Its tail is
// the conversation the CLI was on when the server stopped, which is
// what a re-attach must point the viewer at instead of the launch id.
@@ -4235,6 +4297,9 @@ export class WebServer extends EventEmitter {
sessionWaits.cancelEverything();
approvalInbox.stop();
this.keepWarmService.stop();
// Stops the fetch sweep from starting another run while the server is closing; a git process already
// running is left to finish, which is what a fetch does to a repository nothing else is touching.
this.gitFetchScheduler.stop();
// A post within the debounce window before shutdown would otherwise not reach disk.
// Flushed again after `app.close()` below, for a post that lands in between.
agentInboxPersistence.flush();
+1
View File
@@ -29,6 +29,7 @@ function bareServer(live: string[] = [], persisted: string[] = []): CleanupServe
Object.assign(server, {
sessions: new Map(live.map((id) => [id, {}])),
keepWarmService: { remove: () => {} },
gitFetchScheduler: { remove: () => {} },
store: {
getSession: () => null,
getSessions: () => Object.fromEntries(persisted.map((id) => [id, {}])),
+42
View File
@@ -12,6 +12,7 @@
import { describe, it, expect } from 'vitest';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { SettingsUpdateSchema } from '../src/web/schemas.js';
const publicDir = resolve(import.meta.dirname, '../src/web/public');
const html = readFileSync(resolve(publicDir, 'index.html'), 'utf8');
@@ -195,6 +196,47 @@ describe('App Settings modal structure', () => {
}
});
/**
* Git fetch on an interval (src/git-fetch-scheduler.ts). Both keys are SYNCED, not display keys, because
* the server's scheduler is what acts on them: kept per-device, the scheduler would read nobody's number.
* Off by default, and the interval clamped on save to the same bounds the schema accepts.
*/
it('keeps the Git fetch rows synced, off by default, and inside the bounds the scheduler acts on', () => {
const modal = settingsModal();
const bar = modal.match(/<h4>Bottom bar<\/h4>([\s\S]*?)(?=<div class="set-group-head">)/)?.[1];
expect(bar, 'the Git fetch rows are not in the Bottom bar group').toBeTruthy();
for (const id of ['appSettingsGitFetchEnabled', 'appSettingsGitFetchIntervalSeconds']) {
const at = modal.indexOf(`id="${id}"`);
expect(at, `no element ${id}`).toBeGreaterThan(-1);
const row = modal.slice(modal.lastIndexOf('<div class="set-row"', at), modal.indexOf('</div>', at));
expect(row).toContain('<span class="set-scope">synced</span>');
}
// The number row's own bounds must agree with the schema's, or the browser sends a value the PUT rejects.
expect(modal).toContain('id="appSettingsGitFetchIntervalSeconds" class="set-num" value="300" min="30" max="3600"');
// Display keys are the half of the per-device split that keeps a value off the server.
const displayStart = settingsUi.indexOf('const displayKeys = new Set([');
const displayBlock = settingsUi.slice(displayStart, settingsUi.indexOf(']);', displayStart));
expect(displayBlock).not.toContain('gitFetchEnabled');
expect(displayBlock).not.toContain('gitFetchIntervalSeconds');
// The strip destructure is the other half: an aliased key here never reaches the settings PUT.
expect(settingsUi).not.toMatch(/gitFetch(?:Enabled|IntervalSeconds):\s*_\w+/);
// Declared in the .strict() schema — an undeclared key 400s the whole settings PUT.
expect(SettingsUpdateSchema.safeParse({ gitFetchEnabled: true, gitFetchIntervalSeconds: 300 }).success).toBe(true);
// Off by default (only an explicit true loads as on), and an empty box falls back to the default interval.
expect(settingsUi).toContain(
"document.getElementById('appSettingsGitFetchEnabled').checked = settings.gitFetchEnabled === true;"
);
expect(settingsUi).toContain(
"document.getElementById('appSettingsGitFetchIntervalSeconds').value = settings.gitFetchIntervalSeconds ?? 300;"
);
expect(settingsUi).toMatch(
/gitFetchIntervalSeconds: Math\.min\(\s*3600,\s*Math\.max\(30, parseInt\(document\.getElementById\('appSettingsGitFetchIntervalSeconds'\)\.value, 10\) \|\| 300\)\s*\),/
);
});
it('has retired the modal-tab chrome everywhere, not just here', () => {
// Session Options and Add Case moved onto this same `set-*` surface, so the
// old tab classes have no users left. A reappearance means a modal drifted
+101
View File
@@ -0,0 +1,101 @@
/**
* @fileoverview The Git fetch interval rows (App Settings → Bottom bar, Session Options → Git) in Chinese
* (zh-CN): each label and description runs through the real translator over the real index.html in JSDOM and
* reads in Chinese with no English left beyond the product name and the technical names Git / git fetch, and
* every new key — the save toast in session-ui.js included — is in the dictionary exactly once (a repeated key
* in the object literal silently replaces the first).
*
* The Git tab's Status row is not here: its text is written at runtime by updateGitFetchStatus and carries
* data-i18n-skip, so translating it would rewrite the stamp the code builds. 'sec' is not a key either — only
* whole unit words are ('hours'), so 'sec' stays as written.
*
* Port: N/A.
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { JSDOM } from 'jsdom';
import { afterAll, describe, expect, it } from 'vitest';
const PUBLIC = resolve(import.meta.dirname, '../src/web/public');
const I18N = readFileSync(resolve(PUBLIC, 'i18n.js'), 'utf8');
const INDEX = readFileSync(resolve(PUBLIC, 'index.html'), 'utf8');
// Keys that contain a quote are written escaped in the object literal, so the dictionary is counted unescaped.
const DICT = I18N.replace(/\\'/g, "'").replace(/\\"/g, '"');
type Api = { configure(o: Record<string, string>): void; start(): void };
const ROWS = [
'appSettingsGitFetchEnabled',
'appSettingsGitFetchIntervalSeconds',
'modalGitFetchFollow',
'modalGitFetchEnabled',
'modalGitFetchInterval',
];
/** What may stay Latin: the product names, and Git / git fetch as technical names. */
const leftover = (text: string) =>
text.replace(/\b(Claude Code|Claude|Codeman|Ralph|Git|git|fetch)\b/g, '').match(/[A-Za-z]+/g) ?? [];
function rowStrings(doc: Document, id: string): { label: string; description: string } {
const row = doc.getElementById(id)!.closest('.set-row')!;
const label = row.querySelector('.set-row-label')!;
// The row's own scope marker ('synced') rides inside the label; the dictionary key is the label without it.
const scope = label.querySelector('.set-scope')?.textContent ?? '';
return {
label: label.textContent!.replace(scope, '').trim(),
description: row.querySelector('.set-row-desc')!.textContent!.trim(),
};
}
/** The Git section's blurb, which is not a row. */
function blurb(doc: Document): string {
const section = doc.getElementById('git-tab')!;
return section.querySelector('.set-section-blurb')!.textContent!.trim();
}
const source = new JSDOM(INDEX);
const dom = new JSDOM(INDEX, { runScripts: 'outside-only', url: 'http://localhost/' });
vm.runInContext(I18N, dom.getInternalVMContext(), { filename: 'i18n.js' });
const api = (dom.window as unknown as { CodemanI18n: Api }).CodemanI18n;
api.start();
api.configure({ language: 'zh-CN' });
afterAll(() => {
source.window.close();
dom.window.close();
});
describe('the Git fetch rows in zh-CN', () => {
it.each(ROWS)('translates the %s row, with no English left', (id) => {
const english = rowStrings(source.window.document, id);
const chinese = rowStrings(dom.window.document, id);
expect(english.label.length).toBeGreaterThan(0);
for (const key of ['label', 'description'] as const) {
expect(chinese[key]).not.toBe(english[key]);
expect(leftover(chinese[key])).toEqual([]);
}
});
it('translates the Git section blurb too, which is not a row', () => {
expect(blurb(dom.window.document)).not.toBe(blurb(source.window.document));
expect(leftover(blurb(dom.window.document))).toEqual([]);
});
it("leaves the Status row's runtime text to the code that writes it", () => {
// updateGitFetchStatus builds this row's sentence; a dictionary key for it would overwrite the stamp.
expect(INDEX).toContain('id="gitFetchStatus" data-i18n-skip hidden');
});
it('adds each key to the dictionary once, the save toast included', () => {
const texts = ROWS.flatMap((id) => Object.values(rowStrings(source.window.document, id)));
texts.push(blurb(source.window.document), 'Git fetch settings saved');
// 'sec' is deliberately not a key: only whole unit words are, so the unit stays as the markup writes it.
expect(DICT).not.toMatch(/\n sec: /);
for (const text of texts) {
const quoted = DICT.split(`'${text}'`).length + DICT.split(`"${text}"`).length - 2;
const bare = /^\w+$/.test(text) ? DICT.split(`\n ${text}: `).length - 1 : 0;
expect(quoted + bare, text).toBe(1);
}
});
});
+471
View File
@@ -0,0 +1,471 @@
/**
* @fileoverview The Git fetch interval scheduler (src/git-fetch-scheduler.ts): which sessions a tick runs,
* and which it must not. Every rule is checked by calling `tick(now)` with an explicit clock, so nothing here
* depends on fake timers or on how long a real tick takes — the scheduler owns no timers itself.
*
* The run belongs to the FOLDER, so these tests put two sessions on one folder and expect one fetch that
* both see, and they check the tick's two bounds separately: one shared bound for the fetches of the whole
* tick, and the folders bounded by a bound that cannot be the same semaphore. A folder is due when ANY session
* open on it is due, so the order the sessions were read cannot decide it — that is checked in both orders.
* A run carries the trigger that caused it, and what is published says the run's, not the tick's.
*
* Port: N/A.
*/
import { describe, expect, it, vi } from 'vitest';
import {
GitFetchScheduler,
effectiveGitFetch,
type GitFetchPorts,
type GitFetchSessionView,
} from '../src/git-fetch-scheduler.js';
import {
FETCH_CONCURRENCY,
type GitFetchOptions,
type GitFetchReport,
type GitFetchRun,
type GitFetchSettings,
type GitFetchStatus,
type GitFetchTrigger,
} from '../src/git-fetch.js';
import { DEFAULT_GIT_TIMEOUT_MS, MAX_REPOS } from '../src/git-workspace-status.js';
import type { PathProbeKind } from '../src/utils/bounded-path-probe.js';
const SETTINGS: GitFetchSettings = { enabled: true, intervalSeconds: 300 };
const VIEW = (id: string, extra: Partial<GitFetchSessionView> = {}): GitFetchSessionView => ({
id,
workingDir: `/w/${id}`,
...extra,
});
/** An empty report, in the shape a run produces. */
const report = (cwd: string, name: string): GitFetchReport => ({
state: 'ok',
repos: [{ name, path: '.', ok: true }],
reposTruncated: false,
fetchedAt: Date.now(),
});
/** A run: the report plus the trigger that caused it, which is what the published row has to name. */
const run = (cwd: string, name: string, trigger: GitFetchTrigger = 'interval'): GitFetchRun => ({
report: report(cwd, name),
trigger,
});
type Harness = {
scheduler: GitFetchScheduler;
ports: GitFetchPorts;
/** The folders the tick actually ran, in the order they were picked, with the trigger the tick passed. */
calls: Array<{ cwd: string; opts: GitFetchOptions; trigger: GitFetchTrigger }>;
published: Array<{ id: string; status: GitFetchStatus }>;
/** Every path the tick probed, in order — the probe has to happen before anything is fetched. */
probed: string[];
settings: GitFetchSettings;
dockerReads: number;
/**
* A session that closed: the server calls `remove()` when the session is gone, so this takes it out of the
* ports as well as out of the scheduler. Otherwise a test that removes a session still sees it on the next
* tick, and the folder it was on looks still open.
*/
remove(id: string): void;
};
/** A run the test decides when to let finish, so a slow repository can be held open across ticks. */
function deferred<T>(value: T) {
let resolve = (v: T) => {};
const promise = new Promise<T>((r) => (resolve = r));
return { promise, resolve };
}
/**
* A scheduler over an injected set of ports: nothing here touches a settings file, a repository or the
* server, so what is being pinned is the scheduler's own decisions.
*/
function harness(
sessions: GitFetchSessionView[],
opts: {
settings?: GitFetchSettings;
fetch?: (cwd: string, portOpts: GitFetchOptions, trigger: GitFetchTrigger) => Promise<GitFetchRun>;
/** Default: every path answers as a folder, so a test that does not care about the probe stays quiet. */
probe?: (path: string) => Promise<PathProbeKind>;
} = {}
): Harness {
const customFetch = opts.fetch;
const settings = opts.settings ?? { ...SETTINGS };
const gone = new Set<string>();
const h: Harness = {
scheduler: undefined as unknown as GitFetchScheduler,
ports: undefined as unknown as GitFetchPorts,
calls: [],
published: [],
probed: [],
settings,
dockerReads: 0,
remove: (id) => {
gone.add(id);
h.scheduler.remove(id);
},
};
h.ports = {
sessionIds: () => sessions.filter((s) => !gone.has(s.id)).map((s) => s.id),
getSession: (id) => (gone.has(id) ? undefined : sessions.find((s) => s.id === id)),
readSettings: async () => {
if (h.settings === null) throw new Error('settings.json is mid-write');
return h.settings;
},
dockerWorkspaces: async () => {
h.dockerReads++;
return [];
},
probePath: async (path) => {
h.probed.push(path);
return opts.probe ? await opts.probe(path) : 'directory';
},
fetch: async (cwd, portOpts, trigger) => {
h.calls.push({ cwd, opts: portOpts, trigger });
return customFetch ? customFetch(cwd, portOpts, trigger) : run(cwd, cwd.slice(3), trigger);
},
publish: (id, status) => h.published.push({ id, status }),
};
h.scheduler = new GitFetchScheduler(h.ports);
return h;
}
describe('a quiet tick', () => {
it('costs one settings read and nothing else, because nothing is on', async () => {
const h = harness([VIEW('a'), VIEW('b')], { settings: { enabled: false, intervalSeconds: 300 } });
expect(await h.scheduler.tick(1000)).toBe(0);
expect(h.calls).toEqual([]);
// The probe and the Docker case list are only worth reading once something is actually due.
expect(h.probed).toEqual([]);
expect(h.dockerReads).toBe(0);
});
it('reads settings FRESH every tick, so a live toggle takes effect on the next tick and not at boot', async () => {
const h = harness([VIEW('a')], { settings: { enabled: false, intervalSeconds: 30 } });
await h.scheduler.tick(0);
expect(h.calls.length).toBe(0);
h.settings = { enabled: true, intervalSeconds: 30 };
await h.scheduler.tick(1000);
expect(h.calls.length).toBe(1);
// Turning it off has to stop the fetching, not just stop it starting again later.
h.settings = { enabled: false, intervalSeconds: 30 };
await h.scheduler.tick(2000);
expect(h.calls.length).toBe(1);
});
it('skips this tick only when a settings read fails, because settings.json is rewritten in place', async () => {
const h = harness([VIEW('a')]);
h.settings = null as unknown as GitFetchSettings;
const logged = vi.fn();
h.ports.log = logged;
expect(await h.scheduler.tick(0)).toBe(0);
expect(h.calls).toEqual([]);
expect(logged).toHaveBeenCalled();
h.settings = SETTINGS;
// Nothing was recorded for the failed tick, so the folder is still due at once.
expect(await h.scheduler.tick(1000)).toBe(1);
});
});
describe('the bounded probe', () => {
it('probes the folder before fetching it, and skips anything that is not a directory', async () => {
const kinds = new Map<string, PathProbeKind>([
['/w/file', 'file'],
['/w/unknown', 'unknown'],
['/w/absent', 'absent'],
]);
const h = harness([VIEW('file'), VIEW('unknown'), VIEW('absent'), VIEW('ok')], {
probe: async (path) => kinds.get(path) ?? 'directory',
});
const logged = vi.fn();
h.ports.log = logged;
expect(await h.scheduler.tick(0)).toBe(1);
expect(h.calls.map((c) => c.cwd)).toEqual(['/w/ok']);
// The folders that answered badly were probed and left alone, never fetched.
expect(h.probed).toEqual(['/w/file', '/w/unknown', '/w/absent', '/w/ok']);
expect(logged).toHaveBeenCalledTimes(3);
// `unknown` is never read as `absent`: the log says what it answered rather than what it was assumed.
expect(logged.mock.calls.join(' ')).toContain('unknown');
});
});
describe('who runs', () => {
it('runs every session the app setting covers, once per interval', async () => {
const h = harness([VIEW('a'), VIEW('b')], { settings: { enabled: true, intervalSeconds: 60 } });
await h.scheduler.tick(0);
expect(h.calls.map((c) => c.cwd).sort()).toEqual(['/w/a', '/w/b']);
await h.scheduler.tick(30_000); // not due yet
expect(h.calls.length).toBe(2);
await h.scheduler.tick(60_000);
expect(h.calls.length).toBe(4);
});
it('runs a session that turned itself on even while the app-wide switch is off — that is what a per-session switch has to mean', async () => {
const h = harness([VIEW('plain'), VIEW('own', { gitFetchEnabled: true, gitFetchIntervalSeconds: 30 })], {
settings: { enabled: false, intervalSeconds: 300 },
});
await h.scheduler.tick(0);
expect(h.calls.map((c) => c.cwd)).toEqual(['/w/own']);
// Its own interval, not the app's: due at 30 s, not at 300.
await h.scheduler.tick(30_000);
expect(h.calls.length).toBe(2);
});
it('never fetches a remote or Docker session, exactly as the Git panel excludes them', async () => {
const h = harness([
VIEW('ssh', { remote: { host: 'x' } }),
VIEW('docker', { docker: { container: 'c' } }),
VIEW('local'),
]);
await h.scheduler.tick(0);
expect(h.calls.map((c) => c.cwd)).toEqual(['/w/local']);
});
it('re-checks the Docker rule every tick, so a session whose case became a Docker case stops fetching', async () => {
const sessions = [VIEW('a')];
const h = harness(sessions);
await h.scheduler.tick(0);
expect(h.calls.length).toBe(1);
sessions[0] = { ...sessions[0], docker: { container: 'c' } };
await h.scheduler.tick(400_000);
expect(h.calls.length).toBe(1);
});
it('uses the module defaults for the limit and the timeout, because those settings are per device and never reach the server', async () => {
const h = harness([VIEW('a')]);
await h.scheduler.tick(0);
expect(h.calls[0].opts).toMatchObject({ maxRepos: MAX_REPOS, timeoutMs: DEFAULT_GIT_TIMEOUT_MS });
});
});
describe('one folder, one run', () => {
it('fetches a shared folder once and publishes the result to every session open on it', async () => {
const h = harness([VIEW('a'), { ...VIEW('b'), workingDir: '/w/a' }]);
expect(await h.scheduler.tick(0)).toBe(1); // one folder, not two runs
expect(h.calls.length).toBe(1);
expect(h.published.map((p) => p.id).sort()).toEqual(['a', 'b']);
// Both see the same run, so the panel's row says the same thing in both tabs.
expect(new Set(h.published.map((p) => p.status.failed)).size).toBe(1);
});
it('is due when ANY session open on the folder is due, in either read order, because the clock belongs to the folder and not to whichever session was read first', async () => {
const short = { ...VIEW('short'), workingDir: '/w/shared', gitFetchIntervalSeconds: 30 };
const long = { ...VIEW('long'), workingDir: '/w/shared', gitFetchIntervalSeconds: 300 };
for (const order of [
[short, long],
[long, short],
]) {
const h = harness(order);
// Nothing has run yet, so both are due and both are published from the one run. The folder is probed
// once, not once per session open on it.
expect(await h.scheduler.tick(0)).toBe(1);
expect(h.probed).toEqual(['/w/shared']);
expect(h.published.map((p) => p.id).sort()).toEqual(['long', 'short']);
// Before the short interval elapses neither is due, and the order they were read in cannot change that.
h.published.length = 0;
expect(await h.scheduler.tick(15_000)).toBe(0);
expect(h.published).toEqual([]);
// The short session is past its own interval, so the folder is fetched — once, for both. The run that
// happens covers the long session's interval too, and both still get it because both are open on the
// folder: publishing only the session that made the folder due would leave the other tab on a stale row.
h.published.length = 0;
expect(await h.scheduler.tick(30_000)).toBe(1);
expect(h.calls.length).toBe(2);
expect(h.published.map((p) => p.id).sort()).toEqual(['long', 'short']);
// The long one's own interval comes round, so the folder is due again.
h.published.length = 0;
expect(await h.scheduler.tick(300_000)).toBe(1);
expect(h.published.map((p) => p.id).sort()).toEqual(['long', 'short']);
}
});
it('does not pick a folder again while its run is going, and does not run a second tick over the same selection', async () => {
const ids = Array.from({ length: FETCH_CONCURRENCY + 2 }, (_, i) => `s${i}`);
const gate = deferred<GitFetchRun>(run('/w/first', 'first'));
const h = harness(
ids.map((id) => VIEW(id)),
{
settings: { enabled: true, intervalSeconds: 30 },
fetch: () => gate.promise,
}
);
const first = h.scheduler.tick(0);
await new Promise((resolve) => setImmediate(resolve)); // the first runs are going, the rest are queued
const picked = h.calls.length;
expect(picked).toBe(FETCH_CONCURRENCY);
// The server fires the next tick without waiting. The schedule was stamped at selection, so the folders
// already picked are not picked again, and this tick is skipped while the previous one is still going.
expect(await h.scheduler.tick(15_000)).toBe(0);
expect(h.calls.length).toBe(picked);
gate.resolve(run('/w/first', 'first'));
await first;
// Every folder ran exactly once, and no folder ran twice.
expect(h.calls.length).toBe(ids.length);
expect(new Set(h.calls.map((c) => c.cwd)).size).toBe(ids.length);
});
it('shares one bound across the whole tick instead of giving each folder its own, and bounds the folders with a bound of its own', async () => {
const ids = Array.from({ length: FETCH_CONCURRENCY + 1 }, (_, i) => `s${i}`);
let fetchesLive = 0;
let fetchesPeak = 0;
let foldersLive = 0;
let foldersPeak = 0;
const hold = () => new Promise((resolve) => setImmediate(resolve));
const h = harness(
ids.map((id) => VIEW(id)),
{
// Every folder is handed the SAME limiter for its work, so that work cannot get its own bound: a
// per-call bound would let 5 folders × 6 items run at once. The folders themselves are bounded by a
// DIFFERENT bound, because one semaphore cannot serve both levels — a folder holding a slot and then
// waiting for one for its own fetch is waiting on itself, and the folders that fill the bound are
// exactly the ones blocking it. If the tick used one semaphore for both, this test would hang and fail
// as a timeout rather than as an assertion.
fetch: async (cwd, opts) => {
foldersLive++;
foldersPeak = Math.max(foldersPeak, foldersLive);
await opts.limiter?.([0, 1, 2, 3, 4, 5], async () => {
fetchesLive++;
fetchesPeak = Math.max(fetchesPeak, fetchesLive);
await hold();
fetchesLive--;
});
foldersLive--;
return run(cwd, cwd.slice(3));
},
}
);
await h.scheduler.tick(0);
expect(fetchesPeak).toBe(FETCH_CONCURRENCY); // the tick's ceiling, not each folder's own
expect(foldersPeak).toBe(FETCH_CONCURRENCY);
expect(h.calls.length).toBe(ids.length); // every folder ran, none was left waiting forever
});
it('times the interval from the START of a run, so a slow repository does not push the next one out', async () => {
const slow = deferred<GitFetchRun>(run('/w/a', 'a'));
const h = harness([VIEW('a')], { settings: { enabled: true, intervalSeconds: 30 }, fetch: () => slow.promise });
const first = h.scheduler.tick(0);
await new Promise((resolve) => setImmediate(resolve));
expect(h.calls.length).toBe(1);
// The run takes 200 s, longer than its own interval. Once it lands, the folder is already past due: the
// next tick runs it again instead of waiting another 30 s from when the slow one finished.
slow.resolve(run('/w/a', 'a'));
await first;
expect(await h.scheduler.tick(200_000)).toBe(1);
expect(h.calls.length).toBe(2);
});
});
describe('what a run reports', () => {
it("publishes the run as the interval's own, so the panel can say the number was not asked for", async () => {
const h = harness([VIEW('a')]);
await h.scheduler.tick(0);
expect(h.published).toEqual([
{
id: 'a',
status: { ranAt: expect.any(Number), trigger: 'interval', state: 'ok', repos: 1, failed: 0 },
},
]);
});
it('publishes the trigger of the run that actually happened rather than the trigger the tick asked for, because a tick that joined a click did not fetch anything', async () => {
const h = harness([VIEW('a')], {
// The port is `fetchWorkspaceOnce`, so it can hand back a run a click had already started for this
// folder. The tick asked for its own; the row has to name the run.
fetch: (cwd, _opts, trigger) => {
expect(trigger).toBe('interval');
return Promise.resolve({ report: report(cwd, 'a'), trigger: 'click' });
},
});
await h.scheduler.tick(0);
expect(h.published[0].status.trigger).toBe('click');
});
it("reports a failure instead of retrying harder, and keeps the folder's next run at its own interval", async () => {
const h = harness([VIEW('a')], {
settings: { enabled: true, intervalSeconds: 30 },
fetch: () => Promise.reject(new Error('spawn git ENOENT')),
});
const logged = vi.fn();
h.ports.log = logged;
await h.scheduler.tick(0);
expect(logged).toHaveBeenCalled();
expect(h.published).toEqual([]);
// Still remembered, so the next run is on schedule rather than immediate.
expect(h.scheduler.tracked()).toBe(1);
});
});
describe('the effective choice', () => {
it("a session's own override wins over the app setting", () => {
const settings = { enabled: false, intervalSeconds: 600 };
expect(effectiveGitFetch(VIEW('a', { gitFetchEnabled: true, gitFetchIntervalSeconds: 45 }), settings)).toEqual({
enabled: true,
intervalSeconds: 45,
});
// Half a choice still follows the app for the other half.
expect(effectiveGitFetch(VIEW('b', { gitFetchEnabled: true }), settings)).toEqual({
enabled: true,
intervalSeconds: 600,
});
});
it('re-clamps a persisted interval that can predate the schema bounds', () => {
expect(effectiveGitFetch(VIEW('a', { gitFetchIntervalSeconds: 5 }), SETTINGS)).toEqual({
enabled: true,
intervalSeconds: 30,
});
expect(effectiveGitFetch(VIEW('b', { gitFetchIntervalSeconds: 9000 }), SETTINGS)).toEqual({
enabled: true,
intervalSeconds: 3600,
});
});
});
describe('a session that goes away', () => {
it('takes its own choice with it, but keeps the folder while another session is still open on it', async () => {
const sessions = [VIEW('a'), { ...VIEW('b'), workingDir: '/w/a' }];
const h = harness(sessions);
await h.scheduler.tick(0);
expect(h.scheduler.tracked()).toBe(1);
h.remove('a');
// The run belongs to the clone, so 'b' keeps the folder's schedule and its next run is still on time:
// the choice that got the folder going was 'a's, but the folder is not 'a's.
expect(h.scheduler.tracked()).toBe(1);
await h.scheduler.tick(1000); // not due yet, and 'b' is still open on the folder
expect(h.calls.length).toBe(1);
// The last session open on the folder goes, so the folder is forgotten: a session coming back on it is due
// at once rather than on the schedule the closed one left behind.
h.remove('b');
expect(h.scheduler.tracked()).toBe(0);
sessions.push({ ...VIEW('c'), workingDir: '/w/a' });
await h.scheduler.tick(2000);
expect(h.calls.length).toBe(2); // remembered again, from now
});
it('stops everything after stop(), including a folder that was already due', async () => {
const h = harness([VIEW('a')]);
h.scheduler.stop();
expect(await h.scheduler.tick(0)).toBe(0);
expect(h.calls).toEqual([]);
expect(h.scheduler.tracked()).toBe(0);
});
});
+155
View File
@@ -0,0 +1,155 @@
/**
* @fileoverview The Session Options → Git rows (session-ui.js `updateGitFetchStatus`) as the page drives them: the
* real index.html in JSDOM with the real app.js and session-ui.js loaded into it, and every session update
* delivered through app.js `_onSessionUpdated`, the path a `session:updated` SSE event takes.
*
* 1. A working session sends `session:updated` on each working/idle change, and that path refreshes the open Git
* tab every time, so the control the user is in is left alone: rewriting it put a half-typed "12" back to "300"
* before `onchange` could save it. Enter saves with the field still focused, so the save writes the clamped
* number back itself.
* 2. The route takes one field at a time, so a session can hold half an override. The half it did not choose
* shows the app's value, which is what the scheduler runs it with, never a default.
*
* Port: N/A (no server; the one save is answered by a stub).
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { JSDOM } from 'jsdom';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const PUBLIC = resolve(import.meta.dirname, '../src/web/public');
const SID = 'session-git-rows';
/** The app setting every case here runs against: on, every 900 s. */
const APP = { gitFetchEnabled: true, gitFetchIntervalSeconds: 900 };
type Update = Record<string, unknown> & { id: string };
type TestApp = Record<string, unknown> & {
_onSessionUpdated(data: Update): void;
autoSaveGitFetch(): Promise<void>;
_apiJson: ReturnType<typeof vi.fn>;
};
let dom: JSDOM;
let CodemanApp: { prototype: object };
beforeAll(async () => {
dom = new JSDOM(readFileSync(resolve(PUBLIC, 'index.html'), 'utf8'), {
runScripts: 'outside-only',
url: 'http://localhost/',
});
// app.js starts the app on DOMContentLoaded. Loading it once the document is complete means that never fires
// here, so the real constructor (SSE, WebSocket, timers) never runs in a window with no server behind it.
await new Promise<void>((done) =>
dom.window.document.readyState === 'complete' ? done() : dom.window.addEventListener('load', () => done())
);
const context = dom.getInternalVMContext();
// app.js's last line publishes MobileDetection (mobile-handlers.js), which nothing here otherwise needs.
vm.runInContext('var MobileDetection = { isTouchDevice: () => false };', context);
for (const file of ['constants.js', 'app.js', 'session-ui.js']) {
vm.runInContext(readFileSync(resolve(PUBLIC, file), 'utf8'), context, { filename: file });
}
CodemanApp = vm.runInContext('CodemanApp', context);
});
afterAll(() => dom.window.close());
beforeEach(() => {
(dom.window.document.activeElement as HTMLElement | null)?.blur?.();
});
const el = <T extends HTMLElement = HTMLInputElement>(id: string) => dom.window.document.getElementById(id) as T;
/** An app with the Git tab open on SID and everything the update path draws besides it stubbed. */
function openGitTab(): TestApp {
const app = Object.create(CodemanApp.prototype) as TestApp;
Object.assign(app, {
sessions: new Map(),
_closingSessions: new Set(),
activeSessionId: null,
editingSessionId: SID,
renderSessionTabs: vi.fn(),
updateCost: vi.fn(),
updateSubagentParentNames: vi.fn(),
showToast: vi.fn(),
loadAppSettingsFromStorage: () => ({ ...APP }),
});
return app;
}
describe('Session Options → Git, under session updates', () => {
it('leaves the interval the user is typing alone when a session update arrives, and still refreshes the run line', () => {
const app = openGitTab();
app._onSessionUpdated({ id: SID, status: 'idle', gitFetchEnabled: true, gitFetchIntervalSeconds: 300 });
const num = el('modalGitFetchInterval');
expect(num.disabled).toBe(false);
expect(num.value).toBe('300');
num.focus();
expect(dom.window.document.activeElement).toBe(num);
num.value = '12';
// The working/idle flip that used to put the field back to 300, carrying a scheduled run's result this time.
app._onSessionUpdated({
id: SID,
status: 'busy',
gitFetchEnabled: true,
gitFetchIntervalSeconds: 300,
gitFetch: { ranAt: Date.now(), trigger: 'interval', state: 'ok', repos: 2, failed: 0 },
});
expect(num.value).toBe('12');
expect(el('gitFetchStatus').textContent).toBe('Last run just now on the interval · 2 repositories');
// Only the control the user is in is spared: once they leave it, an update shows the stored value again.
num.blur();
app._onSessionUpdated({ id: SID, status: 'idle', gitFetchEnabled: true, gitFetchIntervalSeconds: 300 });
expect(num.value).toBe('300');
});
it('writes the clamped interval back when Enter saves with the field still focused', async () => {
const app = openGitTab();
app._apiJson = vi.fn(async (_url: string, opts: { body: unknown }) => ({ gitFetchSettings: opts.body }));
app._onSessionUpdated({ id: SID, status: 'idle', gitFetchEnabled: true, gitFetchIntervalSeconds: 300 });
const num = el('modalGitFetchInterval');
num.focus();
num.value = '12';
await app.autoSaveGitFetch();
expect(app._apiJson).toHaveBeenCalledWith(`/api/sessions/${SID}/git-fetch-settings`, {
method: 'POST',
body: { enabled: true, intervalSeconds: 30 },
});
expect(dom.window.document.activeElement).toBe(num);
expect(num.value).toBe('30');
});
});
describe('Session Options → Git, with half an override', () => {
it("shows the app's switch beside an interval-only override, because the scheduler runs it with that switch", () => {
const app = openGitTab();
app._onSessionUpdated({ id: SID, status: 'idle', gitFetchIntervalSeconds: 120 });
expect(el('modalGitFetchFollow').checked).toBe(false);
expect(el('modalGitFetchEnabled').checked).toBe(true);
expect(el('modalGitFetchInterval').value).toBe('120');
// Not following, so both rows are live, and touching either saves what they show.
expect(el('modalGitFetchEnabled').disabled).toBe(false);
expect(el('modalGitFetchInterval').disabled).toBe(false);
});
it("shows the app's interval beside a switch-only override, because the scheduler runs it at that interval", () => {
const app = openGitTab();
app._onSessionUpdated({ id: SID, status: 'idle', gitFetchEnabled: true });
expect(el('modalGitFetchFollow').checked).toBe(false);
expect(el('modalGitFetchEnabled').checked).toBe(true);
expect(el('modalGitFetchInterval').value).toBe('900');
});
it('follows the app on both rows, inert, when the session holds no choice of its own', () => {
const app = openGitTab();
app._onSessionUpdated({ id: SID, status: 'idle' });
expect(el('modalGitFetchFollow').checked).toBe(true);
expect(el('modalGitFetchEnabled').checked).toBe(true);
expect(el('modalGitFetchInterval').value).toBe('900');
expect(el('modalGitFetchEnabled').disabled).toBe(true);
expect(el('modalGitFetchInterval').disabled).toBe(true);
});
});
+770
View File
@@ -0,0 +1,770 @@
/**
* @fileoverview Tests for the Git panel's Fetch button (src/git-fetch.ts): the only git command the Git panel
* runs that writes, and the only one that can run without being asked — which is why it is a click, or an
* interval the user turned on, and why the writing and the hooks it can run are pinned here. Cloning and
* worktree management write too, but they write when the user asked.
*
* Four halves, mirroring the module:
*
* 1. The PURE half — the fixed argv, the `-c` overrides the runner adds ahead of it, the ssh environment the
* runner refuses to override (`fetchEnvFor`), the failure classification, and the two reads the interval
* scheduler depends on: what the settings say (`gitFetchSettingsFrom`) and what a run did
* (`gitFetchStatusFrom`). No spawning.
* 2. The IO half — a REAL git fetching a REAL local bare repo, so that "remote-tracking refs only" is
* proven against git's actual behavior: HEAD, the index and the working tree must be exactly what they
* were while the remote-tracking ref moves. The rest of the half uses an injected runner over real
* repositories on disk, because what is being pinned is WHICH repositories git is allowed to touch.
* 3. The process group — a timed-out fetch has to take its `git-remote-http` helper with it, against a
* server that accepts and never answers, so the assertion is about what is still RUNNING after the answer
* went out. A test that only checked the returned error would pass with the old `execFile` runner, which
* signals the parent only.
* 4. The join (`fetchWorkspaceOnce`) — one run per folder at a time, because two fetches in one clone
* collide on git's ref lock, the bound is ONE limiter shared with the scheduler's tick rather than a bound
* each run gets for itself, and the trigger a join reports is the joined run's, not the joiner's.
*
* Port: N/A (no Codeman server). The process-group test listens on its own loopback socket, on a port the OS
* picks, because the point of that test is a remote that never answers.
*/
import { execFileSync } from 'node:child_process';
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { createServer, type AddressInfo } from 'node:http';
import type { Socket } from 'node:net';
import { tmpdir } from 'node:os';
import { basename, join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { classifyGitFailure, isGitAvailable } from '../src/git-clone.js';
import {
FETCH_CONCURRENCY,
FETCH_CONFIG_ARGS,
FETCH_KILL_ESCALATION_MS,
buildFetchArgs,
clearGitFetchLane,
describeFetchFailure,
fetchEnvFor,
fetchGitWorkspaceOverview,
fetchWorkspaceOnce,
gitFetchSettingsFrom,
gitFetchStatusFrom,
runFetch,
type GitFetchReport,
} from '../src/git-fetch.js';
import { createLimiter, runGit, type GitRunner } from '../src/git-workspace-status.js';
const ENV = {
...process.env,
// As the production runner: git's messages are matched in English, and nothing reads the host's config.
LC_ALL: 'C',
GIT_AUTHOR_NAME: 'T',
GIT_AUTHOR_EMAIL: 't@example.com',
GIT_COMMITTER_NAME: 'T',
GIT_COMMITTER_EMAIL: 't@example.com',
GIT_CONFIG_GLOBAL: '/dev/null',
GIT_CONFIG_NOSYSTEM: '1',
};
const git = (cwd: string, ...args: string[]) =>
execFileSync('git', args, { cwd, env: ENV, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
// ─── The pure half ───────────────────────────────────────────────────────────
describe('buildFetchArgs', () => {
it('pins the argv to a fetch and nothing else', () => {
expect(buildFetchArgs()).toEqual(['fetch', '--quiet']);
// Not just the first word: the whole argv is fixed, so no verb that changes the repository can slip in.
for (const verb of ['commit', 'pull', 'merge', 'checkout', 'reset', 'clean', 'prune', 'gc', 'amend']) {
expect(buildFetchArgs().join(' ')).not.toContain(verb);
}
});
it('names no repository, so the repository can only be the process cwd', () => {
// An operand-shaped argument would let a path or a URL choose the repository; the fixed argv cannot.
for (const arg of buildFetchArgs()) {
expect(arg.startsWith('-')).toBe(arg === '--quiet');
}
});
});
describe('describeFetchFailure', () => {
it("calls a repository with no remote a fact, not a fault, in each of git's wordings", () => {
for (const stderr of [
'fatal: no default remote repository -- use --remote or specify a repository',
'No remote configured',
'fatal: nothing to fetch from remote repository',
]) {
const failure = describeFetchFailure({ stderr });
expect(failure.code).toBe('NO_REMOTE');
expect(failure.message).toMatch(/no remote/i);
expect(failure.message).not.toMatch(/fail|error|unable/i);
}
});
it('writes its own timeout message, because the one to reuse was written for clones', () => {
const failure = describeFetchFailure({ code: 'ETIMEDOUT', stderr: 'fatal: repository not found' });
expect(failure.code).toBe('TIMEOUT');
expect(failure.message).toMatch(/Git status: git timeout/);
expect(failure.message).toMatch(/fetch from a shell/i);
expect(failure.message).not.toBe(classifyGitFailure('fatal: repository not found', true).message);
expect(describeFetchFailure({ killed: true, stderr: '' }).code).toBe('TIMEOUT');
});
it('reuses the network reasons it already knows', () => {
const prompt = "fatal: could not read Username for 'https://github.com': terminal prompts disabled";
expect(describeFetchFailure({ stderr: prompt }).code).toBe('AUTH_REQUIRED');
expect(describeFetchFailure({ stderr: 'git@github.com: Permission denied (publickey).' }).code).toBe(
'AUTH_REQUIRED'
);
expect(describeFetchFailure({ message: 'Error: spawn git ENOENT' }).code).toBe('GIT_MISSING');
expect(describeFetchFailure({ stderr: 'fatal: unable to access: Could not resolve host: nope.invalid' }).code).toBe(
'HOST_UNREACHABLE'
);
});
it('hands the client a redacted, control-stripped tail, never what git printed', () => {
const failure = describeFetchFailure({
stderr: "fatal: unable to access 'https://bob:ghp_secret@github.com/x.git/'\u001b[31m",
});
expect(failure.stderr).toBe("fatal: unable to access 'https://***:***@github.com/x.git/'[31m");
});
});
// ─── The two reads the interval feature depends on ───────────────────────────
describe('gitFetchSettingsFrom', () => {
it('is off until the user turns it on, and 300 s when nothing was chosen', () => {
// Absent means off: a quiet install must not start running git on a timer nobody asked for.
for (const settings of [undefined, {}, { gitFetchEnabled: false }, { gitFetchEnabled: 'true' }]) {
expect(gitFetchSettingsFrom(settings).enabled).toBe(false);
}
expect(gitFetchSettingsFrom({ gitFetchEnabled: true }).enabled).toBe(true);
expect(gitFetchSettingsFrom({}).intervalSeconds).toBe(300);
});
it('clamps a number outside the schema instead of trusting it, because a persisted value can predate the bounds', () => {
expect(gitFetchSettingsFrom({ gitFetchIntervalSeconds: 1 }).intervalSeconds).toBe(30);
expect(gitFetchSettingsFrom({ gitFetchIntervalSeconds: 99999 }).intervalSeconds).toBe(3600);
expect(gitFetchSettingsFrom({ gitFetchIntervalSeconds: 120.6 }).intervalSeconds).toBe(121);
expect(gitFetchSettingsFrom({ gitFetchIntervalSeconds: -300 }).intervalSeconds).toBe(30);
// A hand-edited 0 is still a number it can act on, and acting on it means the smallest interval that runs.
expect(gitFetchSettingsFrom({ gitFetchIntervalSeconds: 0 }).intervalSeconds).toBe(30);
});
it('falls back to the default on a value it cannot act on, which is what a hand-edited settings.json can hold', () => {
for (const raw of ['300', undefined, null, NaN, Infinity, true]) {
expect(gitFetchSettingsFrom({ gitFetchIntervalSeconds: raw }).intervalSeconds, String(raw)).toBe(300);
}
});
});
describe('gitFetchStatusFrom', () => {
it('counts what a run covered and what it could not do, and names the first failure', () => {
const report: GitFetchReport = {
state: 'ok',
repos: [
{ name: 'Codeman', path: '.', ok: true },
{ name: 'api', path: 'api', ok: false, failure: { code: 'NO_REMOTE', message: 'no remote', stderr: '' } },
],
reposTruncated: false,
fetchedAt: 1700,
};
expect(gitFetchStatusFrom(report, 'interval')).toEqual({
ranAt: 1700,
trigger: 'interval',
state: 'ok',
repos: 2,
failed: 1,
firstFailure: { name: 'api', code: 'NO_REMOTE' },
});
});
it('keeps the trigger, because a number the user did not ask for should read differently from one they did', () => {
const empty: GitFetchReport = { state: 'ok', repos: [], reposTruncated: false, fetchedAt: 1000 };
expect(gitFetchStatusFrom(empty, 'click').trigger).toBe('click');
expect(gitFetchStatusFrom(empty, 'interval').trigger).toBe('interval');
});
it('records a state that stopped the run, with nothing to count and no failure to name', () => {
const status = gitFetchStatusFrom(
{ state: 'unsupported', reason: 'docker', repos: [], reposTruncated: false, fetchedAt: 5 },
'interval'
);
expect(status.state).toBe('unsupported');
expect(status.repos).toBe(0);
expect(status.failed).toBe(0);
expect(status.firstFailure).toBeUndefined();
});
});
describe('FETCH_CONFIG_ARGS', () => {
it('turns off the hooks and the maintenance a fetch can otherwise start, pinned without spawning git', () => {
expect(FETCH_CONFIG_ARGS).toEqual([
'-c',
'core.fsmonitor=false',
'-c',
'maintenance.auto=false',
'-c',
'gc.auto=0',
]);
// Read as pairs: a `-c` and the setting it overrides, and every override is one of these three.
for (let i = 0; i < FETCH_CONFIG_ARGS.length; i += 2) {
expect(FETCH_CONFIG_ARGS[i]).toBe('-c');
expect(FETCH_CONFIG_ARGS[i + 1]).toMatch(/^(core\.fsmonitor|maintenance\.auto|gc\.auto)=/);
}
expect(FETCH_CONFIG_ARGS.filter((a) => a !== '-c').sort()).toEqual([
'core.fsmonitor=false',
'gc.auto=0',
'maintenance.auto=false',
]);
});
it('is kept apart from the pinned argv so both can be read without spawning, and the runner composes them in that order', () => {
// The argv the recorded calls pin stays the verb alone: the overrides come from the runner, not from here.
for (const arg of buildFetchArgs()) expect(arg).not.toBe('-c');
// Overrides before the verb, which is where git will take them.
expect([...FETCH_CONFIG_ARGS, ...buildFetchArgs()]).toEqual([...FETCH_CONFIG_ARGS, 'fetch', '--quiet']);
});
});
describe('fetchEnvFor', () => {
const BASE = { HOME: '/home/t', PATH: '/usr/bin' };
it('writes the BatchMode default when nothing else already answered', () => {
const env = fetchEnvFor(BASE, null);
expect(env.GIT_SSH_COMMAND).toContain('BatchMode=yes');
expect(env.GIT_TERMINAL_PROMPT).toBe('0');
});
it('does not override a repository that already chose its own ssh, because that choice is usually the one that works', () => {
const env = fetchEnvFor(BASE, 'ssh -i /home/t/work_key -o ProxyJump=gw');
// The whole point: nothing is written, so git takes the repository's value from its own config.
expect(env.GIT_SSH_COMMAND).toBeUndefined();
// Honouring the repository's ssh is not the same as letting it prompt, so the rest still applies.
expect(env.GIT_TERMINAL_PROMPT).toBe('0');
expect(env.SSH_ASKPASS_REQUIRE).toBe('never');
});
it("the user's own GIT_SSH_COMMAND still beats the repository's, because that is git's rule and not this module's to second-guess", () => {
const env = fetchEnvFor({ ...BASE, GIT_SSH_COMMAND: 'ssh -i /home/t/personal' }, 'ssh -i /repo/key');
expect(env.GIT_SSH_COMMAND).toBe('ssh -i /home/t/personal');
});
it("leaves a GIT_SSH in the server's environment to git, which reads it last and would never see it under a written default", () => {
const env = fetchEnvFor({ ...BASE, GIT_SSH: '/home/t/bin/work-ssh' }, null);
expect(env.GIT_SSH_COMMAND).toBeUndefined();
expect(env.GIT_SSH).toBe('/home/t/bin/work-ssh');
expect(env.GIT_TERMINAL_PROMPT).toBe('0');
});
});
// ─── Real git, real local repository ─────────────────────────────────────────
const gitPresent = isGitAvailable();
let dir: string;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'git-fetch-'));
});
afterEach(() => {
rmSync(dir, { recursive: true, force: true });
});
function initRepo(path: string, remote?: string) {
mkdirSync(path, { recursive: true });
git(path, 'init', '-q', '-b', 'main');
// So a `file://` remote stays allowed for the production runner too, not only for this test's own git calls.
git(path, 'config', 'protocol.file.allow', 'always');
writeFileSync(join(path, 'f.txt'), '1\n');
git(path, 'add', '-A');
git(path, 'commit', '-q', '-m', 'init');
if (remote) git(path, 'remote', 'add', 'origin', remote);
return path;
}
/** Records what each repository was asked to do, and lets real git answer the rest. */
function recordingRunner() {
const calls: Array<[string, string[]]> = [];
const runner: GitRunner = async (cwd, args, opts) => {
calls.push([cwd, args]);
return runGit(cwd, args, opts);
};
return { calls, runner };
}
describe.skipIf(!gitPresent)('fetchGitWorkspaceOverview (real git)', () => {
let work: string;
const snapshot = (path: string) => ({
head: git(path, 'rev-parse', 'HEAD').trim(),
tree: readdirSync(path, { withFileTypes: true })
.filter((e) => e.name !== '.git' && e.isFile())
.sort((a, b) => a.name.localeCompare(b.name))
.map((e) => `${e.name}=${readFileSync(join(path, e.name), 'utf8')}`),
// The global option has to come before the verb, exactly as the read-only status module runs it.
index: git(path, '--no-optional-locks', 'status', '--porcelain=v2').trim(),
});
beforeEach(() => {
const origin = join(dir, 'origin.git');
mkdirSync(origin);
git(origin, 'init', '--bare', '--quiet', '-b', 'main');
work = initRepo(join(dir, 'work'), origin);
git(work, 'push', '-q', 'origin', 'main');
// A commit made elsewhere and pushed: work's origin/main cannot hear about it until a fetch runs.
// This has to be a clone of origin, not a fresh init — a commit on its own root commit is no
// descendant of what origin already holds, so pushing it is rejected as non-fast-forward.
const other = join(dir, 'other');
git(dir, 'clone', '-q', origin, 'other');
git(other, 'config', 'protocol.file.allow', 'always');
writeFileSync(join(other, 'g.txt'), '2\n');
git(other, 'add', '-A');
git(other, 'commit', '-q', '-m', 'second');
git(other, 'push', '-q', 'origin', 'main');
// Left dirty on purpose, so the snapshot has something proving it was not touched.
writeFileSync(join(work, 'untracked.txt'), 'u\n');
writeFileSync(join(work, 'f.txt'), 'modified\n');
});
it('fetches through the production runner, moving remote-tracking refs and writing nothing else', async () => {
// A push does not update the remote-tracking ref, so the fetch is what has to move it: 0 before, 1 after.
expect(git(work, 'rev-list', '--count', 'main..origin/main').trim()).toBe('0');
const before = snapshot(work);
const report = await fetchGitWorkspaceOverview(work);
expect(report.state).toBe('ok');
expect(report.repos).toHaveLength(1);
expect(report.repos[0]).toMatchObject({ name: 'work', path: '.', ok: true });
expect(report.fetchedAt).toBeGreaterThan(0);
expect(snapshot(work)).toEqual(before); // HEAD, the working tree and the index are exactly as they were
expect(git(work, 'rev-list', '--count', 'main..origin/main').trim()).toBe('1');
});
it('fetches exactly the repositories the panel would show, in the panel order', async () => {
const folder = join(dir, 'folder');
for (const name of ['api', 'web']) initRepo(join(folder, name));
mkdirSync(join(folder, 'node_modules', 'pkg'), { recursive: true }); // never a project the panel lists
const { calls, runner } = recordingRunner();
const report = await fetchGitWorkspaceOverview(folder, { git: runner });
expect(report.state).toBe('ok');
expect(report.repos.map((r) => [r.name, r.path])).toEqual([
['api', 'api'],
['web', 'web'],
]);
// Only the fetches, not the resolver's own `rev-parse`: the repositories touched are the point.
// A bounded run does not promise which one starts first, so compare the set.
expect(calls.filter(([, args]) => args[0] === 'fetch').sort()).toEqual([
[join(folder, 'api'), ['fetch', '--quiet']],
[join(folder, 'web'), ['fetch', '--quiet']],
]);
});
it('never reaches an unrelated repository above the workspace', async () => {
const home = join(dir, 'home');
initRepo(home);
const caseDir = join(home, 'case');
mkdirSync(caseDir);
const { calls, runner } = recordingRunner();
const report = await fetchGitWorkspaceOverview(caseDir, { git: runner, home });
expect(report.state).toBe('not-a-repo');
expect(calls.filter(([, args]) => args[0] === 'fetch')).toEqual([]);
});
it('refuses a repository at or inside a Docker case workspace before any git runs', async () => {
initRepo(join(dir, 'repo'));
const { calls, runner } = recordingRunner();
const report = await fetchGitWorkspaceOverview(dir, { git: runner, dockerWorkspaces: [dir] });
expect(report).toMatchObject({ state: 'unsupported', reason: 'docker' });
expect(calls).toEqual([]);
});
it('keeps a repository that could not be fetched, with its reason', async () => {
for (const name of ['ok', 'private']) initRepo(join(dir, 'folder', name));
const runner: GitRunner = async (cwd) => {
if (basename(cwd) === 'private') {
throw Object.assign(new Error('Command failed'), {
stderr: "fatal: could not read Username for 'https://github.com': terminal prompts disabled",
});
}
return '';
};
const report = await fetchGitWorkspaceOverview(join(dir, 'folder'), { git: runner });
expect(report.state).toBe('ok');
const priv = report.repos.find((r) => r.name === 'private');
expect(priv?.ok).toBe(false);
expect(priv?.failure?.code).toBe('AUTH_REQUIRED');
expect(priv?.failure?.message).toMatch(/authentication/i);
expect(report.repos.find((r) => r.name === 'ok')?.ok).toBe(true);
});
it("runs at most FETCH_CONCURRENCY fetches at a time, with the setting's timeout", async () => {
const folder = join(dir, 'folder');
for (let i = 0; i < FETCH_CONCURRENCY + 2; i++) initRepo(join(folder, `r${i}`));
let inFlight = 0;
let max = 0;
const seenTimeouts = new Set<number | undefined>();
const runner: GitRunner = async (cwd, args, opts) => {
seenTimeouts.add(opts?.timeoutMs);
inFlight++;
max = Math.max(max, inFlight);
await new Promise((r) => setTimeout(r, 10));
inFlight--;
return '';
};
const report = await fetchGitWorkspaceOverview(folder, { git: runner, timeoutMs: 7000 });
expect(report.repos).toHaveLength(FETCH_CONCURRENCY + 2);
expect(report.repos.every((r) => r.ok)).toBe(true);
expect(max).toBe(FETCH_CONCURRENCY);
expect(seenTimeouts).toEqual(new Set([7000]));
});
it('answers not-a-repo for a folder that is not a repository, running no fetch', async () => {
const plain = join(dir, 'plain');
mkdirSync(plain);
const { calls, runner } = recordingRunner();
expect(await fetchGitWorkspaceOverview(plain, { git: runner })).toMatchObject({ state: 'not-a-repo', repos: [] });
expect(calls.filter(([, args]) => args[0] === 'fetch')).toEqual([]);
});
});
// ─── The whole tree, not just the git parent ─────────────────────────────────
/** One process as /proc reports it. `null` means it is gone, which is what the last assertion is about. */
interface Proc {
pid: number;
comm: string;
ppid: number;
/** The PROCESS GROUP. `detached: true` puts the fetch in its own, so the negative pid reaches the children. */
pgrp: number;
cmdline: string;
}
/**
* Every process on the machine, as /proc reports it — so this half can only run on Linux, and the fields are
* counted from the closing parenthesis because `comm` can hold spaces.
*
* Membership of the GROUP is what is checked, not parentage: a helper that outlives its parent stops being a
* child of this test process, and a test that looked for children would pass for the wrong reason.
*/
function scanProc(): Proc[] {
const out: Proc[] = [];
for (const entry of readdirSync('/proc')) {
if (!/^\d+$/.test(entry)) continue;
const pid = Number(entry);
try {
const stat = readFileSync(join('/proc', entry, 'stat'), 'utf8');
const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
out.push({
pid,
comm: readFileSync(join('/proc', entry, 'comm'), 'utf8').trim(),
ppid: Number(fields[1]),
pgrp: Number(fields[2]),
cmdline: readFileSync(join('/proc', entry, 'cmdline'), 'utf8')
.replace(/\0/g, ' ')
.trim(),
});
} catch {
/* gone between the listing and the read */
}
}
return out;
}
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
describe.skipIf(!gitPresent)('runFetch (the whole tree, not just the git parent)', () => {
it.skipIf(!existsSync('/proc/self/environ'))(
'kills the helper processes too, so nothing is left running after the timeout',
async () => {
const server = createServer(() => {
// Accept and never answer: git's http helper connects, waits, and stays.
});
const sockets = new Set<Socket>();
server.on('connection', (s) => {
sockets.add(s);
s.on('close', () => sockets.delete(s));
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const port = (server.address() as AddressInfo).port;
try {
const repo = initRepo(join(dir, 'hang'), `http://127.0.0.1:${port}/x.git`);
// The handler goes on the moment the promise is made, not when it is read: the timeout fires while the
// tree is still being looked at, and a rejection with nothing listening to it becomes an unhandled
// rejection instead of this test's answer.
const answered = runFetch(repo, buildFetchArgs(), { timeoutMs: 1_500 }).catch((e) => e);
// The tree has to be a tree before the timeout, or nothing is being proven: git itself, and the helper
// it spawns for an http remote. The helper is a grandchild — `git fetch` runs `git remote-http`, which
// spawns `git-remote-http` — so the group, not the parentage, is what proves it. Each process is
// remembered once found rather than re-scanned: after the kill the group is empty, and a test that kept
// looking would report a tree it had already destroyed. The `git config` read the runner does first is
// a `git` too, so the fetch is found by what it was asked to do.
let parent: Proc | null = null;
let helper: Proc | null = null;
for (let i = 0; i < 60 && !(parent && helper); i++) {
const live = scanProc();
parent =
parent ??
live.find((p) => p.comm === 'git' && p.cmdline.includes('fetch') && p.ppid === process.pid) ??
null;
helper =
helper ??
(parent
? live.find((p) => p.pgrp === parent!.pgrp && p.pid !== parent!.pid && p.cmdline.includes('remote-http'))
: null);
if (!helper) await sleep(25);
}
expect(parent, 'the fetch was never running').not.toBeNull();
expect(helper, 'nothing else in the fetch group, so there was no tree to kill').not.toBeNull();
// `detached: true` puts the fetch in a group of its own, which is why the negative pid is the right
// thing to signal: a helper outside that group would survive a `child.kill()`.
expect(parent!.pgrp).toBe(parent!.pid);
expect(helper!.pgrp).toBe(parent!.pgrp);
const err = (await answered) as { code?: string; killed?: boolean };
expect(err.code).toBe('ETIMEDOUT');
expect(err.killed).toBe(true);
// The answer went out before the tree died — that is the whole point of the fix, and it is why the
// escalation is given its own time here instead of being cancelled when the promise settles.
const deadline = Date.now() + FETCH_KILL_ESCALATION_MS + 2_000;
while (Date.now() < deadline && scanProc().some((p) => p.pgrp === parent!.pgrp)) await sleep(50);
expect(scanProc().some((p) => p.pgrp === parent!.pgrp)).toBe(false);
// Nothing of this test's own is left running either.
await sleep(200);
expect(scanProc().filter((p) => p.ppid === process.pid)).toEqual([]);
} finally {
for (const s of sockets) s.destroy();
server.close();
}
}
);
it('rejects on a non-zero exit instead of resolving empty stdout, so a failure keeps a reason to be read', async () => {
// A remote git cannot read. A repository with no remote is not usable for this: `git fetch --quiet` exits 0
// there on the git this was checked against (2.47.3), so resolving empty stdout would have been the right
// answer and the test would prove nothing. A remote pointing at a path that is not a repository exits 128
// and says why, which is the case the row needs a reason for.
const repo = initRepo(join(dir, 'unreadable-remote'), 'file:///tmp/definitely-not-a-repo-xyz');
let err: unknown = null;
try {
await runFetch(repo, buildFetchArgs());
} catch (e) {
err = e;
}
expect(err, 'a fetch that failed resolved instead of rejecting').not.toBeNull();
const e = err as { code?: unknown; stderr?: string; killed?: boolean };
// The exit code, not the timeout marker, so a caller can still tell a failure from a stall.
expect(e.code).toBe(128);
expect(e.killed).toBe(false);
expect(e.stderr).toMatch(/does not appear to be a git repository/);
expect(describeFetchFailure(err).code).toBe('NOT_FOUND');
});
});
// ─── One bound for the config read and the fetch ─────────────────────────────
describe.skipIf(process.platform === 'win32')('runFetch (one bound for the config read and the fetch)', () => {
it('answers at the timeout when git never answers, not at twice it, because the core.sshCommand read spends part of the bound', async () => {
// A `git` that never answers anything, first on PATH, so the read ahead of the fetch hangs exactly as long as
// the fetch would. Both spawns take PATH from process.env at call time. It records its arguments, so the test
// can tell which of the two it was asked to run.
const bin = join(dir, 'bin');
const calls = join(dir, 'calls');
mkdirSync(bin);
writeFileSync(join(bin, 'git'), `#!/bin/sh\necho "$*" >> '${calls}'\nexec sleep 30\n`, { mode: 0o755 });
const savedPath = process.env.PATH;
process.env.PATH = `${bin}:${savedPath ?? ''}`;
try {
const started = Date.now();
const err = (await runFetch(dir, buildFetchArgs(), { timeoutMs: 1_000 }).catch((e) => e)) as {
code?: unknown;
killed?: boolean;
};
const elapsed = Date.now() - started;
expect(err.code).toBe('ETIMEDOUT');
expect(err.killed).toBe(true);
expect(describeFetchFailure(err).code).toBe('TIMEOUT');
// One bound, not one per spawn: the read used all of it, so the fetch got nothing and was not started
// (2019 ms here before the fix, when the fetch was armed with a fresh timeout of its own).
expect(elapsed).toBeGreaterThanOrEqual(950);
expect(elapsed).toBeLessThan(1_600);
expect(readFileSync(calls, 'utf8').trim().split('\n')).toEqual(['config --get core.sshCommand']);
} finally {
if (savedPath === undefined) delete process.env.PATH;
else process.env.PATH = savedPath;
}
});
});
// ─── One run per folder, and one bound for the whole tick ────────────────────
describe.skipIf(!gitPresent)('fetchWorkspaceOnce (the join)', () => {
// The resolver still runs real git, so these need real repositories on disk; what is injected is only the
// fetch, because what is being pinned here is the joining, not git's answer.
beforeEach(() => {
// The lane is module state: a run left in it by the previous test would be joined by the next one.
clearGitFetchLane();
});
it('joins a run already going for the same folder instead of starting a second git fetch in the same clone', async () => {
const folder = join(dir, 'folder');
initRepo(join(folder, 'api'));
let releaseRun = () => {};
const held = new Promise<void>((resolve) => (releaseRun = resolve));
let running = () => {};
const runStarted = new Promise<void>((resolve) => (running = resolve));
let firstRunFetches = 0;
const firstRunner: GitRunner = async (cwd, args) => {
if (args[0] === 'fetch') {
firstRunFetches++;
running();
await held;
}
return '';
};
const first = fetchWorkspaceOnce(folder, { git: firstRunner }, 'interval');
await runStarted; // the run is going, and still going
// A click while that run is working the folder: it joins, so it never touches git at all — not even the
// resolver's own probe, because it does not resolve anything for itself.
let joinerCalls = 0;
const joinerRunner: GitRunner = async () => {
joinerCalls++;
return '';
};
const joiner = fetchWorkspaceOnce(folder, { git: joinerRunner }, 'click');
releaseRun();
const answer = await first;
// The joiner gets that same run's answer, including its limits: the point is not to fetch twice.
expect(await joiner).toBe(answer);
expect(joinerCalls).toBe(0);
expect(firstRunFetches).toBe(1);
});
it('a join reports the trigger of the run it joined, not the trigger that made it ask, because a click that fetched nothing cannot claim the fetch', async () => {
const folder = join(dir, 'folder');
initRepo(join(folder, 'api'));
let releaseRun = () => {};
const held = new Promise<void>((resolve) => (releaseRun = resolve));
let running = () => {};
const runStarted = new Promise<void>((resolve) => (running = resolve));
const runner: GitRunner = async (cwd, args) => {
if (args[0] === 'fetch') {
running();
await held;
}
return '';
};
// The tick got there first; the click is the joiner.
const intervalRun = fetchWorkspaceOnce(folder, { git: runner }, 'interval');
await runStarted;
const joinerRun = fetchWorkspaceOnce(folder, { git: async () => '' }, 'click');
releaseRun();
const run = await intervalRun;
expect(await joinerRun).toBe(run); // one run, not two answers
expect(run.trigger).toBe('interval');
// The row the panel shows is built from the run that ran, so it names the interval.
expect(gitFetchStatusFrom(run.report, run.trigger).trigger).toBe('interval');
});
it('keys the join on the resolved folder, so the same folder written two ways is one run', async () => {
const folder = join(dir, 'folder');
initRepo(join(folder, 'api'));
let releaseRun = () => {};
const held = new Promise<void>((resolve) => (releaseRun = resolve));
let running = () => {};
const runStarted = new Promise<void>((resolve) => (running = resolve));
let fetches = 0;
const firstRunner: GitRunner = async (cwd, args) => {
if (args[0] === 'fetch') {
fetches++;
running();
await held;
}
return '';
};
const first = fetchWorkspaceOnce(folder, { git: firstRunner }, 'click');
await runStarted;
// Two sessions on one folder reach it by different spellings; the scheduler keys by `resolve`.
let joinerCalls = 0;
const joinerRunner: GitRunner = async () => {
joinerCalls++;
return '';
};
const second = fetchWorkspaceOnce(join(dir, 'folder', '.'), { git: joinerRunner }, 'click');
releaseRun();
expect(await second).toBe(await first);
expect(joinerCalls).toBe(0);
expect(fetches).toBe(1);
});
it('releases the folder when a run lands, so the next click is a new run and not an old answer', async () => {
const folder = join(dir, 'folder');
initRepo(join(folder, 'api'));
let fetches = 0;
const runner: GitRunner = async (cwd, args) => {
if (args[0] === 'fetch') fetches++;
return '';
};
const firstRun = await fetchWorkspaceOnce(folder, { git: runner }, 'interval');
expect(fetches).toBe(1);
const secondRun = await fetchWorkspaceOnce(folder, { git: runner }, 'click');
expect(fetches).toBe(2);
// A run that is its own reports its own trigger; only a joiner borrows the trigger of the run it joined.
expect(firstRun.trigger).toBe('interval');
expect(secondRun.trigger).toBe('click');
});
it('bounds a whole tick with the limiter it is handed, because two runs given a bound each would get twice the bound', async () => {
const left = join(dir, 'left');
const right = join(dir, 'right');
for (let i = 0; i < FETCH_CONCURRENCY + 1; i++) {
initRepo(join(left, `l${i}`));
initRepo(join(right, `r${i}`));
}
const held = () => new Promise((resolve) => setTimeout(resolve, 10));
// Only the fetches go through the limiter, so only they are counted here: the resolver's own probe is
// not a bounded git process.
const counting =
(state: { live: number; peak: number }): GitRunner =>
async (cwd, args) => {
if (args[0] !== 'fetch') return '';
state.live++;
state.peak = Math.max(state.peak, state.live);
await held();
state.live--;
return '';
};
// The scheduler hands every folder in the tick the SAME limiter, so the bound is the tick's, not the run's.
const shared = { live: 0, peak: 0 };
const sharedRunner = counting(shared);
const limiter = createLimiter(FETCH_CONCURRENCY);
await Promise.all([
fetchGitWorkspaceOverview(left, { git: sharedRunner, limiter }),
fetchGitWorkspaceOverview(right, { git: sharedRunner, limiter }),
]);
expect(shared.peak).toBe(FETCH_CONCURRENCY);
// Without a shared limiter each run bounds only its own call, which is the failure the scheduler is there
// to prevent: two folders at FETCH_CONCURRENCY each, so twice as many git processes as the rule says.
const alone = { live: 0, peak: 0 };
const aloneRunner = counting(alone);
await Promise.all([
fetchGitWorkspaceOverview(left, { git: aloneRunner }),
fetchGitWorkspaceOverview(right, { git: aloneRunner }),
]);
expect(alone.peak).toBe(2 * FETCH_CONCURRENCY);
});
});
+145
View File
@@ -29,6 +29,7 @@ describe('Git status indicator in a real browser', () => {
let repoSession: string;
let plainSession: string;
const gitStatusRequests: string[] = [];
const gitFetchRequests: string[] = [];
const settingsPutStatuses: number[] = [];
const write = (rel: string, text = 'x\n') => writeFileSync(join(repo, rel), text);
@@ -91,6 +92,9 @@ describe('Git status indicator in a real browser', () => {
page.on('request', (r) => {
// The API route only: the page also loads /git-status-ui.js, whose URL contains the same words.
if (/\/api\/sessions\/[^/]+\/git-status/.test(r.url())) gitStatusRequests.push(r.url());
// Anchored: the per-case Git settings route (/git-fetch-settings) is a different route, and a bare
// /git-fetch test would count its PUTs as fetches. The fetch route carries the limits as a query.
if (/\/api\/sessions\/[^/]+\/git-fetch(\?|$)/.test(r.url())) gitFetchRequests.push(r.url());
});
page.on('response', (r) => {
if (r.request().method() === 'PUT' && r.url().endsWith('/api/settings')) settingsPutStatuses.push(r.status());
@@ -514,6 +518,147 @@ describe('Git status indicator in a real browser', () => {
await refresh();
}, 40000);
it('puts Fetch in the header row, between Refresh and Close', async () => {
const order = await page.evaluate(() =>
[...document.querySelectorAll('.git-status-actions button')].map((b) => b.getAttribute('aria-label'))
);
expect(order).toEqual(['Refresh git status', 'Fetch git status', 'Close git status']);
// A repository the panel can read is a repository Fetch can fetch, so the button is live here.
expect(await page.evaluate(() => document.getElementById('gitStatusFetchBtn')!.disabled)).toBe(false);
});
it('Fetch fetches for real, moves the behind number, and reports what it brought', async () => {
// A second clone pushes a commit this repository has not fetched, so its remote-tracking ref is stale:
// the panel cannot show a `behind` number until a fetch runs. That is what the footer means by
// "as of the last fetch", and the number only becomes current by the button.
const other = join(root, 'other-clone');
git(root, 'clone', '-q', join(root, 'origin.git'), other);
writeFileSync(join(other, 'from-elsewhere.txt'), 'y\n');
git(other, 'add', '-A');
git(other, 'commit', '-q', '-m', 'from elsewhere');
git(other, 'push', '-q');
await refresh();
expect(await page.textContent('#gitStatusBody')).not.toMatch(/behind/);
const before = gitFetchRequests.length;
await page.click('#gitStatusFetchBtn');
await page.waitForFunction(
() => /↓ 1 behind/.test(document.getElementById('gitStatusBody')?.textContent ?? ''),
null,
{ timeout: 20000 }
);
expect(gitFetchRequests.length).toBe(before + 1);
// The same limits the status route gets go with the fetch, so the two agree on which repositories count.
expect(gitFetchRequests.at(-1)).toMatch(/maxRepos=12/);
expect(await page.locator('.git-status-chip', { hasText: 'behind' }).textContent()).toBe('↓ 1 behind');
expect(await page.textContent('#gitStatusBody .git-status-fetch-summary')).toMatch(
/^Fetched .+: 1 of 1 repository\.$/
);
expect(await page.locator('#gitStatusBody .git-status-fetch-row').count()).toBe(0);
// The 15 s poll rebuilds the whole body, so the note has to come from the renderer, not from the click.
await refresh();
expect(await page.locator('#gitStatusBody .git-status-fetch-summary').count()).toBe(1);
const foot = (await page.textContent('#gitStatusFooter')) ?? '';
expect(foot).toMatch(/Read-only apart from Fetch/);
// No longer "only when you click": an interval the user turned on fetches too, and the footer says so.
expect(foot).toMatch(/interval/);
// The chip itself says how it got current, so the number is not read as live.
expect(await page.locator('.git-status-chip', { hasText: 'behind' }).getAttribute('title')).toMatch(/interval/);
rmSync(other, { recursive: true, force: true });
}, 30000);
it('a repository Fetch could not fetch keeps its row and shows why', async () => {
await page.route('**/api/sessions/*/git-fetch*', (route) =>
route.fulfill({
contentType: 'application/json',
body: JSON.stringify({
success: true,
data: {
state: 'ok',
reposTruncated: false,
fetchedAt: Date.now(),
repos: [
{ name: 'fetchable', path: 'fetchable', ok: true },
{
name: 'private',
path: '/srv/private',
ok: false,
failure: { code: 'AUTH', message: 'could not read the remote' },
},
],
},
}),
})
);
await page.click('#gitStatusFetchBtn');
await page.waitForFunction(() =>
/could not read the remote/.test(document.getElementById('gitStatusBody')?.textContent ?? '')
);
// The summary counts what landed, and the failure is named rather than folded into the count. The
// summary is the panel's first note line, so the count is read off it, not off the whole body.
expect(await page.textContent('#gitStatusBody .git-status-fetch-summary')).toMatch(
/^Fetched .+: 1 of 2 repositories\.$/
);
const row = (await page.textContent('#gitStatusBody .git-status-fetch-row')) ?? '';
expect(row).toContain('private');
expect(row).toContain('⚠ could not read the remote');
expect(await page.locator('#gitStatusBody .git-status-fetch-row').count()).toBe(1);
// Git text is untrusted: the row is text, never markup.
expect(await page.$('#gitStatusBody img')).toBeNull();
await page.unroute('**/api/sessions/*/git-fetch*');
}, 30000);
it('one click means one fetch: the button is busy while it runs and a second call is ignored', async () => {
let slow = true;
await page.route('**/api/sessions/*/git-fetch*', async (route) => {
if (slow) await new Promise((r) => setTimeout(r, 1500));
await route.continue();
});
page.setDefaultTimeout(6000);
await page.click('#gitStatusFetchBtn');
await page.waitForFunction(() => (window as any).app._gitFetchInFlight === true);
const busy = await page.evaluate(() => {
const b = document.getElementById('gitStatusFetchBtn')!;
return { ariaBusy: b.getAttribute('aria-busy'), disabled: b.disabled };
});
expect(busy.ariaBusy).toBe('true');
// Disabled is what stops a second click reaching the handler, so one click is one fetch per repository.
expect(busy.disabled).toBe(true);
const during = gitFetchRequests.length;
await page.evaluate(() => void (window as any).app.fetchGitStatusNow());
expect(gitFetchRequests.length).toBe(during);
slow = false;
// The flag goes false before the re-render that follows it, so wait for the button itself, not the flag:
// reading it right at the flip catches the panel mid-render.
await page.waitForFunction(
() => {
const b = document.getElementById('gitStatusFetchBtn')!;
return (window as any).app._gitFetchInFlight === false && !b.disabled && !b.getAttribute('aria-busy');
},
null,
{ timeout: 15000 }
);
// The handler is still asleep: unrouting without waiting fails the run as an unhandled rejection.
await page.unrouteAll({ behavior: 'wait' });
page.setDefaultTimeout(30000);
}, 30000);
it('Fetch is inert for a session nothing can be fetched for', async () => {
await select(plainSession);
await page.waitForFunction(
() => /No git repository here/.test(document.getElementById('gitStatusBody')?.textContent ?? ''),
null,
{ timeout: 15000 }
);
expect(await page.evaluate(() => document.getElementById('gitStatusFetchBtn')!.disabled)).toBe(true);
await select(repoSession);
await page.waitForFunction(() => document.getElementById('gitStatusFetchBtn')!.disabled === false, null, {
timeout: 15000,
});
await page.waitForSelector('#gitStatusPanel.visible');
}, 30000);
it('closing the panel resets it; turning the setting off hides the button, closes the panel and stops polling', async () => {
await page.click('.git-status-actions button[aria-label="Close git status"]');
expect(await page.isVisible('#gitStatusPanel')).toBe(false);
+17
View File
@@ -11,6 +11,7 @@ import type {
SessionStatus,
SessionRemote,
} from '../../src/types.js';
import type { GitFetchStatus } from '../../src/git-fetch.js';
/**
* Enhanced mock session for testing RespawnController.
@@ -69,6 +70,22 @@ export class MockSession extends EventEmitter {
this.keepWarm = status;
return changed;
}
/**
* Mirrors the Git fetch interval surface on Session (src/git-fetch.ts): the case's own override, `undefined`
* for either half meaning the app-wide setting applies, and what the scheduler last reported.
*/
gitFetchEnabled: boolean | undefined = undefined;
gitFetchIntervalSeconds: number | undefined = undefined;
setGitFetchSettings(enabled: boolean | undefined, intervalSeconds: number | undefined): void {
this.gitFetchEnabled = enabled;
this.gitFetchIntervalSeconds = intervalSeconds;
}
gitFetch: GitFetchStatus | null = null;
setGitFetchStatus(status: GitFetchStatus): boolean {
const changed = JSON.stringify(status) !== JSON.stringify(this.gitFetch);
this.gitFetch = status;
return changed;
}
private _activeChildProcesses: { pid: number; command: string }[] = [];
ralphTracker: null = null;
writeBuffer: string[] = [];
+258
View File
@@ -11,6 +11,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createRouteTestHarness } from './_route-test-utils.js';
import { registerGitStatusRoutes } from '../../src/web/routes/git-status-routes.js';
import { clearGitStatusCache, runGit, type GitRunner } from '../../src/git-workspace-status.js';
import { clearGitFetchLane, fetchWorkspaceOnce } from '../../src/git-fetch.js';
const ENV = {
...process.env,
@@ -44,6 +45,8 @@ async function setup(
beforeEach(() => {
clearGitStatusCache();
// The fetch lane is module state: a run left in it by the previous test would be joined by the next one.
clearGitFetchLane();
dir = mkdtempSync(join(tmpdir(), 'git-status-route-'));
});
afterEach(() => {
@@ -353,6 +356,261 @@ describe('GET /api/sessions/:id/git-status limits', () => {
});
});
describe('POST /api/sessions/:id/git-fetch', () => {
/** Records what each repository was asked to do, and lets real git answer the rest. */
function recordingRunner() {
const calls: Array<[string, string[]]> = [];
const seenTimeouts: Array<number | undefined> = [];
const runner: GitRunner = async (cwd, args, opts) => {
calls.push([cwd, args]);
seenTimeouts.push(opts?.timeoutMs);
return execFileSyncGit(cwd, args);
};
return { calls, seenTimeouts, runner, fetches: () => calls.filter(([, args]) => args[0] === 'fetch') };
}
it('runs one fetch per repository the window would show, in the session working directory', async () => {
for (const name of ['api', 'web']) {
mkdirSync(join(dir, name));
git(join(dir, name), 'init', '-q', '-b', 'main');
}
const { calls, fetches, runner } = recordingRunner();
const { app } = await setup({ git: runner });
const res = await app.inject({ method: 'POST', url: '/api/sessions/test-session-1/git-fetch' });
expect(res.statusCode).toBe(200);
const data = res.json().data;
expect(data.state).toBe('ok');
expect(data.repos.map((r: { name: string; path: string }) => [r.name, r.path])).toEqual([
['api', 'api'],
['web', 'web'],
]);
expect(data.repos.every((r: { ok: boolean }) => r.ok)).toBe(true);
// A bounded run does not promise which repository starts first, so compare the set.
expect(fetches().sort()).toEqual([
[join(dir, 'api'), ['fetch', '--quiet']],
[join(dir, 'web'), ['fetch', '--quiet']],
]);
// Every repository git was asked to touch sits under the session folder, and under nothing else.
for (const [cwd] of calls) expect(cwd.startsWith(dir)).toBe(true);
});
it('keeps a repository it could not fetch, with its reason, and says which ones it fetched', async () => {
for (const name of ['ok', 'private']) {
mkdirSync(join(dir, name));
git(join(dir, name), 'init', '-q', '-b', 'main');
}
const { fetches, runner } = recordingRunner();
const injected: GitRunner = async (cwd, args, opts) => {
const recorded = runner(cwd, args, opts); // records the call before deciding what git would have said
if (args[0] === 'fetch' && cwd === join(dir, 'private')) {
throw Object.assign(new Error('Command failed'), {
stderr: "fatal: could not read Username for 'https://github.com': terminal prompts disabled",
});
}
return recorded;
};
const { app } = await setup({ git: injected });
const data = (await app.inject({ method: 'POST', url: '/api/sessions/test-session-1/git-fetch' })).json().data;
const priv = data.repos.find((r: { name: string }) => r.name === 'private');
expect(priv?.ok).toBe(false);
expect(priv?.failure?.code).toBe('AUTH_REQUIRED');
expect(data.repos.find((r: { name: string }) => r.name === 'ok')?.ok).toBe(true);
// Both repositories are still in the list, so both were attempted: a failure does not cancel the run.
expect(fetches()).toHaveLength(2);
});
it('redacts credentials git may have echoed back before the failure reaches the client', async () => {
git(dir, 'init', '-q', '-b', 'main');
// Only the fetch is faked: the resolver still needs its own `rev-parse` to find the repository at all.
const runner: GitRunner = async (cwd, args) => {
if (args[0] === 'fetch') {
throw Object.assign(new Error('Command failed'), {
stderr: "fatal: unable to access 'https://bob:ghp_secret@github.com/x.git/'\u001b[31m",
});
}
return execFileSyncGit(cwd, args);
};
const { app } = await setup({ git: runner });
const data = (await app.inject({ method: 'POST', url: '/api/sessions/test-session-1/git-fetch' })).json().data;
expect(data.state).toBe('ok');
expect(data.repos[0].failure.stderr).toBe("fatal: unable to access 'https://***:***@github.com/x.git/'[31m");
});
it.each([
['remote', { host: 'h', user: 'u' }],
['docker', { container: 'c' }],
])('does not run git for a %s session and says it is unsupported', async (kind, value) => {
git(dir, 'init', '-q', '-b', 'main');
const { calls, fetches, runner } = recordingRunner();
const { app } = await setup({ git: runner });
session[kind] = value;
const res = await app.inject({ method: 'POST', url: '/api/sessions/test-session-1/git-fetch' });
expect(res.statusCode).toBe(200);
expect(res.json().data).toMatchObject({ state: 'unsupported', reason: kind });
expect(fetches()).toEqual([]);
expect(calls).toEqual([]); // the resolver never ran either: the refusal comes before any git
});
it('refuses a repository inside a Docker case workspace before any git runs', async () => {
git(dir, 'init', '-q', '-b', 'main');
const { calls, fetches, runner } = recordingRunner();
const { app } = await setup({ git: runner, dockerWorkspaces: [realpathSync(dir)] });
const res = await app.inject({ method: 'POST', url: '/api/sessions/test-session-1/git-fetch' });
expect(res.json().data).toMatchObject({ state: 'unsupported', reason: 'docker' });
expect(fetches()).toEqual([]);
expect(calls).toEqual([]);
});
it('answers not-a-repo for a folder that is not a repository, running no fetch', async () => {
const { fetches, runner } = recordingRunner();
const { app } = await setup({ git: runner });
const data = (await app.inject({ method: 'POST', url: '/api/sessions/test-session-1/git-fetch' })).json().data;
expect(data.state).toBe('not-a-repo');
// The resolver looked once and found nothing, so nothing was fetched — and never guessed a repository.
expect(fetches()).toEqual([]);
});
it("publishes what the click got as the session's own fetch state, naming the trigger the user asked for", async () => {
git(dir, 'init', '-q', '-b', 'main');
const { runner } = recordingRunner();
const { app, ctx } = await setup({ git: runner });
const res = await app.inject({ method: 'POST', url: '/api/sessions/test-session-1/git-fetch' });
expect(res.statusCode).toBe(200);
// The response body is one tab's copy of the run; the state is what every other tab open on the same
// folder sees, and a number the user did not ask for has to read differently from one they did.
expect(session.gitFetch).toMatchObject({ trigger: 'click', state: 'ok', repos: 1, failed: 0 });
expect(ctx.persistSessionState).toHaveBeenCalled();
expect(ctx.broadcast).toHaveBeenCalled();
});
it('joins a run already going for the same folder instead of starting a second git process in the same clone', async () => {
git(dir, 'init', '-q', '-b', 'main');
let releaseRun = () => {};
const held = new Promise<void>((resolve) => (releaseRun = resolve));
let running = () => {};
const runStarted = new Promise<void>((resolve) => (running = resolve));
const fetches: string[] = [];
const runner: GitRunner = async (cwd, args) => {
if (args[0] === 'fetch') {
fetches.push(cwd);
running();
await held;
}
return execFileSyncGit(cwd, args);
};
const { app } = await setup({ git: runner });
const first = app.inject({ method: 'POST', url: '/api/sessions/test-session-1/git-fetch' });
await runStarted; // the run is going, and still going
// A click from another tab open on the same clone. Two fetches there would collide on git's ref lock, so
// this one joins the run already going rather than starting its own.
const second = app.inject({ method: 'POST', url: '/api/sessions/test-session-1/git-fetch' });
// Assert the join BEFORE releasing the run: the lane entry goes away when the run finishes, so releasing
// first would let the run complete before this request reached the lane, and it would then be entitled to
// start its own fetch — a test that passes for the wrong reason. One tick of the loop is enough for both
// handlers to reach the lane while the run is still held open.
await new Promise((resolve) => setImmediate(resolve));
expect(fetches).toHaveLength(1); // one run, and the second request is waiting on it, not working
releaseRun();
const a = (await first).json().data;
const b = (await second).json().data;
expect(b).toEqual(a); // both tabs get the same run's answer, not a partial one
});
it('publishes the trigger of the run the click joined, because a click that fetched nothing cannot report itself as the fetch', async () => {
git(dir, 'init', '-q', '-b', 'main');
let releaseRun = () => {};
const held = new Promise<void>((resolve) => (releaseRun = resolve));
let running = () => {};
const runStarted = new Promise<void>((resolve) => (running = resolve));
const fetches: string[] = [];
const runner: GitRunner = async (cwd, args) => {
if (args[0] === 'fetch') {
fetches.push(cwd);
running();
await held;
}
return execFileSyncGit(cwd, args);
};
const { app, ctx } = await setup({ git: runner });
// The interval tick got to this clone first. The click joins it, so the row the other tabs see has to name
// the interval — the user clicked, but nothing this click did was a fetch. The request is left open, not
// awaited: awaiting it here would wait on the run this test is holding, and the test would wait on itself.
const intervalRun = fetchWorkspaceOnce(dir, { git: runner }, 'interval');
await runStarted;
const res = app.inject({ method: 'POST', url: '/api/sessions/test-session-1/git-fetch' });
await new Promise((resolve) => setImmediate(resolve));
releaseRun();
const run = await intervalRun;
const body = (await res).json().data;
expect(body).toEqual(run.report); // the run it joined, not a partial answer of its own
// Asserted after the run, so this can only pass if the click reached the lane and joined: a click that had
// started its own fetch would make this two, and would have nothing to call the interval.
expect(fetches).toHaveLength(1);
expect(session.gitFetch).toMatchObject({ trigger: 'interval', state: 'ok', repos: 1, failed: 0 });
expect(ctx.broadcast).toHaveBeenCalled();
});
it('404s an unknown session, running no fetch', async () => {
const { calls, fetches, runner } = recordingRunner();
const { app } = await setup({ git: runner });
expect((await app.inject({ method: 'POST', url: '/api/sessions/nope/git-fetch' })).statusCode).toBe(404);
expect(fetches()).toEqual([]);
expect(calls).toEqual([]);
});
it('multi-user: another user’s session is not found, and no fetch runs', async () => {
process.env.CODEMAN_MULTIUSER = '1';
git(dir, 'init', '-q', '-b', 'main');
const { fetches, runner } = recordingRunner();
const { app } = await setup({ git: runner, authUser: { username: 'bob', role: 'user' } });
session.owner = 'alice';
expect((await app.inject({ method: 'POST', url: '/api/sessions/test-session-1/git-fetch' })).statusCode).toBe(404);
expect(fetches()).toEqual([]);
});
it('honours maxRepos and timeout (seconds) for a fetch too, clamped, and reports the limit it used', async () => {
for (const n of ['a', 'b', 'c']) {
mkdirSync(join(dir, n));
git(join(dir, n), 'init', '-q', '-b', 'main');
}
const { seenTimeouts, fetches, runner } = recordingRunner();
const { app } = await setup({ git: runner });
const post = async (query: string) => {
const res = await app.inject({ method: 'POST', url: `/api/sessions/test-session-1/git-fetch${query}` });
expect(res.statusCode).toBe(200);
return res.json().data as { repoLimit: number; repos: Array<{ name: string }> };
};
const fetchCount = () => fetches().length;
const ran = async (query: string, expected: number) => {
const before = fetchCount();
const data = await post(query);
expect(fetchCount() - before).toBe(expected);
return data;
};
const limited = await ran('?maxRepos=2&timeout=7', 2);
expect(limited.repos.map((r) => r.name)).toEqual(['a', 'b']);
expect(limited).toMatchObject({ reposTruncated: true, repoLimit: 2 }); // the window has to say three were found
expect(new Set(seenTimeouts)).toEqual(new Set([7000]));
const wild = await ran('?maxRepos=9999&timeout=1', 3);
expect(wild.repoLimit).toBe(50); // clamped to MAX_REPOS_LIMIT, so one request cannot scan the whole disk
expect(seenTimeouts.at(-1)).toBe(5000);
const junk = await ran('?maxRepos=abc&timeout=xyz', 3);
expect(junk.repoLimit).toBe(12);
expect(seenTimeouts.at(-1)).toBe(30_000);
// A repeated key reaches the route as an array: it means "default", never a 500.
await ran('?timeout=5&timeout=6', 3);
expect(seenTimeouts.at(-1)).toBe(30_000);
});
});
function execFileSyncGit(cwd: string, args: string[]): Promise<string> {
return Promise.resolve(execFileSync('git', ['--no-optional-locks', ...args], { cwd, env: ENV, encoding: 'utf8' }));
}
@@ -0,0 +1,104 @@
/**
* `POST /api/sessions/:id/git-fetch-settings` (session-routes.ts): the per-case half of the fetch interval
* (src/git-fetch-scheduler.ts) — the case's own switch and its own interval. `null` on either half clears
* that half so the app-wide setting applies again, and a body that names one row leaves the other as it was,
* because the Session Options rows save on their own. Refused for remote and Docker cases, the same rule the
* Git panel and the scheduler use. app.inject(), no port.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import Fastify, { type FastifyInstance } from 'fastify';
import fastifyCookie from '@fastify/cookie';
import { createMockRouteContext, type MockRouteContext } from '../mocks/index.js';
import { installRouteErrorHandler } from '../../src/web/route-error-handler.js';
import { registerSessionRoutes } from '../../src/web/routes/session-routes.js';
interface Harness {
app: FastifyInstance;
ctx: MockRouteContext;
}
async function createHarness(): Promise<Harness> {
const app = Fastify({ logger: false });
await app.register(fastifyCookie);
const ctx = createMockRouteContext();
registerSessionRoutes(app, ctx);
installRouteErrorHandler(app);
await app.ready();
return { app, ctx };
}
describe('POST /api/sessions/:id/git-fetch-settings', () => {
let harness: Harness;
beforeEach(async () => {
harness = await createHarness();
});
afterEach(async () => {
await harness.app.close();
});
const post = (payload: unknown) =>
harness.app.inject({ method: 'POST', url: `/api/sessions/${harness.ctx._sessionId}/git-fetch-settings`, payload });
it('stores the case’s own choice, persists and broadcasts it', async () => {
const res = await post({ enabled: true, intervalSeconds: 120 });
expect(res.statusCode).toBe(200);
expect(JSON.parse(res.body).data.gitFetchSettings).toEqual({ enabled: true, intervalSeconds: 120 });
expect(harness.ctx._session.gitFetchEnabled).toBe(true);
expect(harness.ctx._session.gitFetchIntervalSeconds).toBe(120);
expect(harness.ctx.persistSessionState).toHaveBeenCalled();
});
it('answers `null` for a case that follows the app, which is what the Session Options row shows', async () => {
const data = JSON.parse((await post({})).body).data.gitFetchSettings;
expect(data).toEqual({ enabled: null, intervalSeconds: null });
});
it('clears the override on null so the app-wide setting applies again', async () => {
await post({ enabled: true, intervalSeconds: 120 });
const res = await post({ enabled: null, intervalSeconds: null });
expect(res.statusCode).toBe(200);
expect(harness.ctx._session.gitFetchEnabled).toBeUndefined();
expect(harness.ctx._session.gitFetchIntervalSeconds).toBeUndefined();
expect(JSON.parse(res.body).data.gitFetchSettings).toEqual({ enabled: null, intervalSeconds: null });
});
it('leaves the other half as it was when only one row was saved', async () => {
await post({ enabled: true });
expect(harness.ctx._session.gitFetchIntervalSeconds).toBeUndefined(); // still following the app on that half
const res = await post({ intervalSeconds: 90 });
expect(JSON.parse(res.body).data.gitFetchSettings).toEqual({ enabled: true, intervalSeconds: 90 });
});
it('rejects an interval outside the schema bounds, storing nothing, because that is what the scheduler acts on', async () => {
// `null` is NOT on this list: it is the schema's way of clearing the override, tested above.
for (const raw of [29, 3601, 12.5, '120', true]) {
const res = await post({ enabled: true, intervalSeconds: raw });
expect(res.statusCode, String(raw)).toBe(400);
}
expect(harness.ctx._session.gitFetchEnabled).toBeUndefined();
expect(harness.ctx.persistSessionState).not.toHaveBeenCalled();
});
it.each([
['remote', { host: 'h', user: 'u' }],
['docker', { container: 'c' }],
])('refuses a %s case, storing nothing', async (kind, value) => {
(harness.ctx._session as unknown as Record<string, unknown>)[kind] = value;
const res = await post({ enabled: true, intervalSeconds: 120 });
expect(JSON.parse(res.body)).toMatchObject({ success: false, errorCode: 'INVALID_INPUT' });
expect(harness.ctx._session.gitFetchEnabled).toBeUndefined();
expect(harness.ctx.persistSessionState).not.toHaveBeenCalled();
});
it('404s an unknown session, storing nothing', async () => {
const res = await harness.app.inject({
method: 'POST',
url: '/api/sessions/nope/git-fetch-settings',
payload: { enabled: true },
});
expect(res.statusCode).toBe(404);
expect(harness.ctx.persistSessionState).not.toHaveBeenCalled();
});
});
+41 -2
View File
@@ -34,13 +34,18 @@ function methodBody(signature: string): string {
return sessionUi.slice(start, sessionUi.indexOf('\n },', start));
}
const TABS = ['respawn', 'context', 'ralph', 'summary'];
const TABS = ['respawn', 'context', 'ralph', 'summary', 'git'];
describe('Session Options modal structure', () => {
it('keeps every element openSessionOptions and switchOptionsTab touch by id', () => {
const modal = optionsModal();
const ids = new Set<string>();
for (const sig of ['openSessionOptions(sessionId)', 'switchOptionsTab(tabName)', 'getRalphConfig()']) {
for (const sig of [
'openSessionOptions(sessionId)',
'switchOptionsTab(tabName)',
'getRalphConfig()',
'updateGitFetchStatus(sessionId)',
]) {
for (const m of methodBody(sig).matchAll(/getElementById\('([A-Za-z0-9_-]+)'\)/g)) ids.add(m[1]);
}
// openSessionOptions also drives elements outside this modal (tabs, toasts);
@@ -83,6 +88,40 @@ describe('Session Options modal structure', () => {
expect(modal.match(/<button[^>]*data-tab="context"[^>]*>/)?.[0]).not.toContain('data-claude-only');
});
it('keeps the Git rail entry for every local session, and hides it for the ones nothing is ever fetched for', () => {
const modal = optionsModal();
// A shell session has repositories too, so Git must not ride the Claude-only flag.
expect(modal.match(/<button[^>]*data-tab="git"[^>]*>/)?.[0]).not.toContain('data-claude-only');
const open = methodBody('openSessionOptions(sessionId)');
expect(open).toContain('.set-rail-item[data-tab="git"]');
// Remote and Docker sessions answer 'unsupported' on both git routes and the scheduler never fetches them,
// so the entry goes the same way the Claude-only ones do.
expect(open).toMatch(/gitTabBtn\.style\.display = session\.remote \|\| session\.docker \? 'none' : ''/);
});
it('makes the Git rows inert while a session follows the app, the way the keep-warm rows go inert', () => {
const modal = optionsModal();
const update = methodBody('updateGitFetchStatus(sessionId)');
expect(update).toContain('set-row-disabled');
expect(update).toContain('el.disabled = follows');
// Decided from BOTH fields: a half-choice means the session is not following, and the half that still
// follows shows the app's value while the other shows its own — a switch-only check would gray out a live row.
expect(update).toMatch(
/follows = session\.gitFetchEnabled === undefined && session\.gitFetchIntervalSeconds === undefined/
);
// Following saves null on both halves, which is what clears the override on the route.
const save = methodBody('async autoSaveGitFetch()');
expect(save).toContain('{ enabled: null, intervalSeconds: null }');
// Saves through the helper that says whether the call went through: `_apiPost` hands back the Response
// without checking it, so a body the route refused (a 400) read as a save, and the panel showed a choice
// the server never took.
expect(save).toContain('this._apiJson(`/api/sessions/${this.editingSessionId}/git-fetch-settings`');
expect(save).toContain('if (!data)');
expect(save).not.toMatch(/await this\._apiPost\(/);
// The status row is runtime text this method writes, so translating it would rewrite the stamp.
expect(modal).toContain('id="gitFetchStatus" data-i18n-skip hidden');
});
it('uses the shared settings surface rather than the modal-tab chrome', () => {
const modal = optionsModal();
expect(modal).toContain('class="modal-content modal-lg set-shell"');
+32
View File
@@ -40,6 +40,7 @@ describe('restoreMuxSessions() hands back every persisted user setting', () => {
['auto-compact', /session\.setAutoCompact\(/],
['auto-resume', /session\.restoreAutoResume\(/],
['nice priority', /session\.setNice\(/],
['git fetch', /gitFetchEnabled:\s*savedState\?\.gitFetchEnabled/],
])('%s', (_label, pattern) => {
expect(body).toMatch(pattern);
});
@@ -58,6 +59,15 @@ describe('restoreMuxSessions() hands back every persisted user setting', () => {
expect(body, `restoreMuxSessions lacks ${call}`).toContain(call);
}
});
it('re-applies the fetch choice only when the case actually chose one', () => {
// `undefined` is what "follows the app" means here, so a restore that called the setter unconditionally
// would hand every case the app default as if it had picked it, and the half-choice rows would read wrong.
const reapply = functionBody('reapplyPersistedSessionState');
expect(reapply).toMatch(
/if \(saved\.gitFetchEnabled !== undefined \|\| saved\.gitFetchIntervalSeconds !== undefined\)[\s\S]{0,160}session\.setGitFetchSettings\(saved\.gitFetchEnabled, saved\.gitFetchIntervalSeconds\)/
);
});
});
describe('the setters round-trip through toState()', () => {
@@ -83,4 +93,26 @@ describe('the setters round-trip through toState()', () => {
imageWatcherEnabled: true,
});
});
it('round-trips the fetch choice, and keeps a case that follows the app unchosen', () => {
const chose = new Session({ workingDir: '/tmp', mode: 'shell' });
chose.setGitFetchSettings(true, 120);
const state = chose.toState();
expect(state).toMatchObject({ gitFetchEnabled: true, gitFetchIntervalSeconds: 120 });
const rebuilt = new Session({
workingDir: '/tmp',
mode: 'shell',
gitFetchEnabled: state.gitFetchEnabled,
gitFetchIntervalSeconds: state.gitFetchIntervalSeconds,
});
expect(rebuilt.toState()).toMatchObject({ gitFetchEnabled: true, gitFetchIntervalSeconds: 120 });
// Undefined is the whole meaning of "follows the app": a restore that wrote the app default into the
// case would make it look like the case had picked it, and the row would stop following.
const follower = new Session({ workingDir: '/tmp', mode: 'shell' });
follower.setGitFetchSettings(undefined, undefined);
expect(follower.toState().gitFetchEnabled).toBeUndefined();
expect(follower.toState().gitFetchIntervalSeconds).toBeUndefined();
});
});
+7 -4
View File
@@ -140,11 +140,13 @@ describe('the Bottom bar settings group in zh-CN', () => {
/** What may stay Latin here: the git and Docker names, and the product name. */
const left = (text: string) => text.replace(/\b(Git|git|Docker|Codeman)\b/g, '').match(/[A-Za-z]+/g) ?? [];
it("finds the heading and the four Git status rows, #543's two included (the check is not vacuous)", () => {
expect(englishGroup.size).toBe(9);
it("finds the heading and the six Git rows, #543's two included and the fetch pair among them (the check is not vacuous)", () => {
expect(englishGroup.size).toBe(13);
expect(englishGroup.get('heading')).toBe('Bottom bar');
expect(englishGroup.get('appSettingsGitStatusMaxRepos label')).toBe('Git status: max repositories');
expect(englishGroup.get('appSettingsGitStatusTimeout label')).toBe('Git status: git timeout');
expect(englishGroup.get('appSettingsGitFetchEnabled label')).toBe('Git fetch on an interval');
expect(englishGroup.get('appSettingsGitFetchIntervalSeconds label')).toBe('Git fetch: how often');
});
it('translates the heading, every label and every description, with no English left', () => {
@@ -167,7 +169,8 @@ describe('the Bottom bar settings group in zh-CN', () => {
expect([...englishGroup.values()].filter((s) => t.t(s) !== s)).toEqual([]);
en.window.close();
const repeated = [...englishGroup.values()].filter((s) => {
const key = s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// A key with an apostrophe is written escaped in the object literal, so the pattern must allow both spellings.
const key = s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/'/g, "(?:\\\\)?'");
return (I18N.match(new RegExp(`^\\s*(?:'${key}'|"${key}"|${key}):`, 'gm')) ?? []).length !== 1;
});
expect(repeated).toEqual([]);
@@ -179,6 +182,6 @@ describe('the Bottom bar settings group in zh-CN', () => {
const labels = [...doc.querySelectorAll('#gitStatusPanel .git-status-actions button')].map((b) =>
b.getAttribute('aria-label')
);
expect(labels).toEqual(['刷新 Git 状态', '关闭 Git 状态']);
expect(labels).toEqual(['刷新 Git 状态', '拉取 Git 状态', '关闭 Git 状态']);
});
});