mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-17 03:39:33 +01:00
feat(git): a Fetch button in the Git status header, and an interval for it app-wide and per case
Fetch is the only git command Codeman runs that writes, and the only one that runs a repository's own fetch-post hook, so it stays behind a click and off by default. The Git status window's header row gains Fetch; App Settings -> Bottom bar gains the switch and the interval, synced because the scheduler acts on them, and Session Options -> Git overrides both per case. The scheduler reads settings fresh each tick, times the interval from the start of a run, never overlaps runs, and re-checks the Docker and remote rules every tick before any git runs. Nothing but remote-tracking refs moves: HEAD, the index and the working tree are proven unchanged against real git while origin/main advances. Tests: src/git-fetch.ts and the scheduler, the per-case settings route, the synced/display setting split, the two new i18n rows, and the Fetch block of the Git status browser suite.
This commit is contained in:
1 parent
3e06f3c141
commit
9432d9f9e2
35 files changed
+2340
-39
No files matched your search
@@ -234,7 +234,9 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
|
||||
**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 Codeman runs that WRITES, and the only one that runs a repository's own `fetch-post` hook — 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, since an agent is often working in the same repository. ⚠️ 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, and bounded: `MAX_REPOS`/`MAX_REPOS_LIMIT` (12/50), `FETCH_CONCURRENCY` (4), `MAX_FETCH_OUTPUT_BYTES` (2 MB) and the git timeout per spawn. ⚠️ `buildFetchArgs()` is `['fetch', '--quiet']` and must stay verb-invariant (`test/git-workspace-status.test.ts`). ⚠️ 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-case override wins even while the app-wide switch is off, the interval is timed from the run START, runs never overlap, and remote/Docker cases are re-checked every tick. ⚠️ 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-case state rides `SessionUpdated` (no new SSE event) as `gitFetch`. Tests: `test/git-fetch.test.ts`, `test/git-fetch-scheduler.test.ts`, `test/routes/session-routes-git-fetch-settings.test.ts`, `test/git-fetch-i18n.test.ts`, `test/app-settings-structure.test.ts`, `test/session-options-structure.test.ts`, and the Fetch block of `test/git-status.browser.test.ts` (browser suite, not in the gate).
|
||||
|
||||
**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)
|
||||
|
||||
@@ -302,7 +304,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.
|
||||
- **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.
|
||||
- **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`.
|
||||
|
||||
@@ -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 case). 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)
|
||||
|
||||
@@ -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 Codeman runs that writes, and it writes remote-tracking refs only — nothing commits, checks out, merges or touches the working tree, so an agent working in the same repository is not disturbed. It runs on that click, or on the interval below and never otherwise, and `git fetch` is exactly the command that runs a repository's own `fetch-post` hook, 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, one spawn per repository with the same per-command timeout, `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.
|
||||
|
||||
`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 case 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 case 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. Remote and Docker cases 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`.
|
||||
|
||||
@@ -84,8 +84,20 @@ 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 case with no choice 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 case, and that override wins even while the app switch is off; a case 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) case, and a repository a container can write to is refused
|
||||
before any git runs. Both default to off because `git fetch` is the one git command Codeman runs that
|
||||
writes, and the one that runs a repository's own hooks.
|
||||
|
||||
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*
|
||||
|
||||
@@ -245,12 +245,23 @@ 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 case that is on, and **Session Options → Git** overrides both the
|
||||
switch and the interval for one case — a case that turned itself on runs even while the app-wide
|
||||
switch is off, and nothing is ever fetched for Docker or remote (SSH) cases.
|
||||
|
||||
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 one git command here that
|
||||
writes, and the one that runs a repository's own hooks, which is why nothing runs on a timer until you
|
||||
opt in. 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. 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
|
||||
|
||||
@@ -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 cases 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
|
||||
// ============================================================================
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* @fileoverview Git fetch on an interval: the cases 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 place Codeman runs a git command that writes, and on a
|
||||
* timer it is the only one that can run without being asked — which is why the whole feature is off until
|
||||
* the user turns it on, in Settings → Bottom bar, per case 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 case can override both the switch and the
|
||||
* interval; a case 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 case that turned itself on still runs even while the
|
||||
* app-wide switch is off — that is what a per-case switch has to mean.
|
||||
* - Remote and Docker cases are never fetched, exactly as the Git panel excludes them, and the Docker
|
||||
* workspace roots are checked again every tick, so a case that became a Docker case stops fetching at
|
||||
* the next tick.
|
||||
* - One run per case at a time: a tick skips a case still being fetched rather than stacking runs on it.
|
||||
* - At most `FETCH_CONCURRENCY` cases at a time across all of them, because each is a git process.
|
||||
* - 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 case keeps its reason 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 { getErrorMessage } from './types.js';
|
||||
import {
|
||||
FETCH_CONCURRENCY,
|
||||
MAX_GIT_FETCH_INTERVAL_SECONDS,
|
||||
MIN_GIT_FETCH_INTERVAL_SECONDS,
|
||||
gitFetchStatusFrom,
|
||||
type GitFetchOptions,
|
||||
type GitFetchReport,
|
||||
type GitFetchSettings,
|
||||
type GitFetchStatus,
|
||||
} from './git-fetch.js';
|
||||
import { clampInt, DEFAULT_GIT_TIMEOUT_MS, MAX_REPOS, mapLimited } from './git-workspace-status.js';
|
||||
|
||||
/** What the scheduler needs from a case: 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;
|
||||
}
|
||||
|
||||
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[]>;
|
||||
fetch(cwd: string, opts: GitFetchOptions): Promise<GitFetchReport>;
|
||||
publish(id: string, status: GitFetchStatus): void;
|
||||
log?(message: string): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* What one case 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 case last started a run; timed from the start, not the end. */
|
||||
private readonly lastRunAt = new Map<string, number>();
|
||||
private readonly inFlight = new Set<string>();
|
||||
private stopped = false;
|
||||
|
||||
constructor(ports: GitFetchPorts) {
|
||||
this.ports = ports;
|
||||
}
|
||||
|
||||
/** One tick: fetch every case that is on and due. Returns how many ran. */
|
||||
async tick(now = Date.now()): Promise<number> {
|
||||
if (this.stopped) return 0;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
const due: GitFetchSessionView[] = [];
|
||||
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 || this.inFlight.has(id)) continue;
|
||||
const started = this.lastRunAt.get(id);
|
||||
if (started !== undefined && now - started < effective.intervalSeconds * 1000) continue;
|
||||
due.push(view);
|
||||
}
|
||||
if (!due.length) 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();
|
||||
await mapLimited(due, FETCH_CONCURRENCY, async (view) => {
|
||||
this.inFlight.add(view.id);
|
||||
// The clock starts at the run, so a slow repository does not shift the case's own schedule.
|
||||
this.lastRunAt.set(view.id, now);
|
||||
try {
|
||||
const report = await this.ports.fetch(view.workingDir, {
|
||||
dockerWorkspaces,
|
||||
maxRepos: MAX_REPOS,
|
||||
timeoutMs: DEFAULT_GIT_TIMEOUT_MS,
|
||||
});
|
||||
this.ports.publish(view.id, gitFetchStatusFrom(report, 'interval'));
|
||||
} catch (err) {
|
||||
// The run that failed keeps its reason in the panel's own row; here only the case-level failure is
|
||||
// worth a line, because nothing else would say a scheduled fetch could not run at all.
|
||||
this.ports.log?.(`git fetch: ${view.id} could not run: ${getErrorMessage(err)}`);
|
||||
} finally {
|
||||
this.inFlight.delete(view.id);
|
||||
}
|
||||
});
|
||||
return due.length;
|
||||
}
|
||||
|
||||
/** A case that closed or was detached: its schedule and its in-flight flag go with it. */
|
||||
remove(id: string): void {
|
||||
this.lastRunAt.delete(id);
|
||||
this.inFlight.delete(id);
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
this.lastRunAt.clear();
|
||||
this.inFlight.clear();
|
||||
}
|
||||
|
||||
/** Cases 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
/**
|
||||
* @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 one place Codeman
|
||||
* runs a git command that writes, and on a timer it is also the only one that can run without being asked.
|
||||
* Nothing here commits, checks out, merges or touches the working tree: `git fetch` updates remote-tracking
|
||||
* refs and nothing else, so an agent working in the same repository is not disturbed.
|
||||
*
|
||||
* Same split as git-clone.ts: the pure half (`buildFetchArgs`, `describeFetchFailure`,
|
||||
* `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 runs a
|
||||
* repository's own hooks (`fetch-post`), which is why a timer only runs it after the user opts in.
|
||||
* - Bounded: the git timeout from Settings → Bottom bar per repository, `FETCH_CONCURRENCY` at a time,
|
||||
* `MAX_REPOS_LIMIT` repositories at most, and a hard `timeout` on each spawn.
|
||||
* - 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.
|
||||
* - 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 } from 'node:child_process';
|
||||
import { basename, relative } from 'node:path';
|
||||
import { promisify } from 'node:util';
|
||||
import { classifyGitFailure, gitNonInteractiveEnv, sanitizeGitOutput, type GitFailureCode } from './git-clone.js';
|
||||
import {
|
||||
DEFAULT_GIT_TIMEOUT_MS,
|
||||
mapLimited,
|
||||
resolveOverviewLimits,
|
||||
resolveWorkspaceRepos,
|
||||
type GitRunner,
|
||||
} from './git-workspace-status.js';
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
/** Fetches in flight at once: each is one git process, and a folder can hold up to `MAX_REPOS_LIMIT`. */
|
||||
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;
|
||||
|
||||
/** 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'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
/** Fetch is allowed to write refs, so this runner does not carry `--no-optional-locks`: fetch takes a required lock anyway. */
|
||||
export const runFetch: GitRunner = async (cwd, args, opts) => {
|
||||
const { stdout } = await execFileAsync('git', ['-c', 'core.fsmonitor=false', ...args], {
|
||||
cwd,
|
||||
timeout: opts?.timeoutMs ?? DEFAULT_GIT_TIMEOUT_MS,
|
||||
maxBuffer: MAX_FETCH_OUTPUT_BYTES,
|
||||
env: gitNonInteractiveEnv(),
|
||||
});
|
||||
return stdout;
|
||||
};
|
||||
|
||||
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.
|
||||
*/
|
||||
export interface GitFetchStatus {
|
||||
ranAt: number;
|
||||
trigger: 'click' | 'interval';
|
||||
/** 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 };
|
||||
}
|
||||
|
||||
export function gitFetchStatusFrom(report: GitFetchReport, trigger: GitFetchStatus['trigger']): 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;
|
||||
}
|
||||
|
||||
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 failures = await mapLimited(dirs, FETCH_CONCURRENCY, (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(),
|
||||
};
|
||||
}
|
||||
@@ -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,8 @@ 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[]> {
|
||||
/** Run `fn` over `items` with at most `limit` in flight, keeping the input order. Shared with the fetch path. */
|
||||
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 +635,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 +644,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 ?? []);
|
||||
|
||||
@@ -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`),
|
||||
@@ -1172,6 +1173,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 {
|
||||
|
||||
@@ -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 case; undefined = follow the app-wide default. Persisted. */
|
||||
private _gitFetchEnabled: boolean | undefined;
|
||||
/** Seconds between this case'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 case (see `gitFetchEnabled`). */
|
||||
gitFetchEnabled?: boolean;
|
||||
/** Restored Git fetch interval for this case (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 case; undefined means the app-wide setting applies. */
|
||||
get gitFetchEnabled(): boolean | undefined {
|
||||
return this._gitFetchEnabled;
|
||||
}
|
||||
|
||||
/** Interval override for this case; undefined means the app-wide setting applies. */
|
||||
get gitFetchIntervalSeconds(): number | undefined {
|
||||
return this._gitFetchIntervalSeconds;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the case'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,
|
||||
|
||||
@@ -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,16 @@ 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 case'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 case's runs; absent = follow the app-wide `gitFetchIntervalSeconds` default. */
|
||||
gitFetchIntervalSeconds?: number;
|
||||
/** What this case's last fetch did; ephemeral, never restored. */
|
||||
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 */
|
||||
|
||||
@@ -2455,6 +2455,9 @@ 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 case's result on this same event, so an open Session Options modal on
|
||||
// that case shows it without polling its own (session-ui.js: updateGitFetchStatus).
|
||||
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) {
|
||||
|
||||
@@ -9,9 +9,11 @@
|
||||
* 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 only when the user clicks Fetch in that window's header (`POST /api/sessions/:id/git-fetch`,
|
||||
* src/git-fetch.ts): the only git command Codeman runs that writes, and only on that click. 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 +267,75 @@ 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 Codeman runs that writes, and it
|
||||
* updates remote-tracking refs only, so an agent working in the same repository is not disturbed. One
|
||||
* click means one fetch per repository: the button is busy and a second click is ignored while it runs.
|
||||
* 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 +384,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 +451,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 +526,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) {
|
||||
|
||||
+27
-2
@@ -351,6 +351,7 @@
|
||||
Delete: '删除',
|
||||
Remove: '移除',
|
||||
Edit: '编辑',
|
||||
Fetch: '拉取',
|
||||
Refresh: '刷新',
|
||||
Back: '返回',
|
||||
Next: '下一步',
|
||||
@@ -523,8 +524,8 @@
|
||||
// #543's two included). Keys are the trimmed label text, without the scope tag.
|
||||
'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 one git command here that writes — runs only 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 命令)只在您点击该窗口中的拉取按钮时运行,或在您开启了下方的定时后按间隔运行。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,8 +535,32 @@
|
||||
'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)。仓库位于较慢的网络共享上时请调高此值。',
|
||||
'Fetch git status': '拉取 Git 状态',
|
||||
'Refresh git status': '刷新 Git 状态',
|
||||
'Close git status': '关闭 Git 状态',
|
||||
// Git fetch on an interval (App Settings → Bottom bar, Session Options → Git, and the save toast in
|
||||
// session-ui.js). 'Status' and 'Git' are not added: the first already has a key, the second stays a
|
||||
// technical name, and the status row's text is written at runtime.
|
||||
"Whether Codeman fetches this case's repositories on a timer.": '{name} 是否按间隔拉取此案例的仓库。',
|
||||
'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 one git command Codeman runs that writes, and the one that runs a repository\'s own hooks, so nothing runs on a timer until you turn it on. A case can override both the switch and the interval in Session Options → Git.':
|
||||
'按间隔为 Git 窗口列出的仓库运行拉取,这样“落后”的数字无需点击就是最新的。默认关闭:这是 {name} 运行的唯一会写入的 git 命令,也是唯一会运行仓库自身钩子的命令,所以在您开启之前不会有任何定时运行。案例可以在“会话选项 → Git”中同时覆盖开关和间隔。',
|
||||
'Git fetch: how often': 'Git 定时拉取:多久一次',
|
||||
'Seconds between runs for a case that has no override of its own (30 to 3600, default 300). Only a case that is on — here, or in Session Options → Git — is fetched.':
|
||||
'没有自己覆盖设置的案例,两次运行之间的秒数(30 到 3600,默认 300)。只有已开启的案例——这里,或在“会话选项 → Git”——才会被拉取。',
|
||||
'Fetch on an interval': '按间隔拉取',
|
||||
"Fetching is the only git command Codeman runs that writes, and the only one that runs a repository's own hooks, so nothing runs on a timer until you turn it on — here, or in App Settings → Bottom bar. The panel's Fetch button is always just a click.":
|
||||
'拉取是 {name} 运行的唯一会写入的 git 命令,也是唯一会运行仓库自身钩子的命令,所以在您开启之前(这里,或“应用设置 → 底部栏”)不会有任何定时运行。该窗口中的拉取按钮始终只是一次点击。',
|
||||
'Follow the app setting': '跟随应用设置',
|
||||
'Uses the app-wide switch and interval for this case. Switch it off to pick your own.':
|
||||
'为此案例使用应用级的开关和间隔。关闭它即可自行选择。',
|
||||
'Fetch this case': '拉取此案例',
|
||||
'Runs on its own even while the app-wide switch is off: a case that turned itself on means exactly that.':
|
||||
'即使应用级开关关闭也自行运行:一个自己开启的案例正是这个意思。',
|
||||
'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 定时拉取设置已保存',
|
||||
Panels: '面板',
|
||||
Monitor: '监视器',
|
||||
'Project Insights': '项目洞察',
|
||||
|
||||
@@ -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">↻</button>
|
||||
<button class="btn-icon-sm" id="gitStatusFetchBtn" onclick="app.fetchGitStatusNow()" title="Fetch" aria-label="Fetch git status">⤓</button>
|
||||
<button class="btn-icon-sm" onclick="app.closeGitStatusPanel()" title="Close" aria-label="Close git status">×</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1331,6 +1332,12 @@
|
||||
<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: a case that has not turned fetching on shows nothing here, so the section only
|
||||
earns its place once the feature is in use. -->
|
||||
<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 +1726,53 @@
|
||||
</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 case'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 Codeman runs that writes, and the only one that runs a repository's own hooks, so nothing runs on a timer until you turn it on — here, or in App Settings → Bottom bar. The panel's Fetch button is always just a click.</p>
|
||||
<div class="set-group-body">
|
||||
<!-- Live from the case's own last run (session-ui.js: updateGitFetchStatus). -->
|
||||
<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 case. 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 case</span>
|
||||
<span class="set-row-desc">Runs on its own even while the app-wide switch is off: a case that turned itself on means exactly that.</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 +2250,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 one git command here that writes — runs only 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 +2275,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 one git command Codeman runs that writes, and the one that runs a repository's own hooks, so nothing runs on a timer until you turn it on. A case 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 case that has no override of its own (30 to 3600, default 300). Only a case that is on — here, or in Session Options → Git — is fetched.</span>
|
||||
</div>
|
||||
<input type="number" id="appSettingsGitFetchIntervalSeconds" class="set-num" value="300" min="30" max="3600" step="1">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -2685,6 +2685,9 @@ Object.assign(CodemanApp.prototype, {
|
||||
document.getElementById('modalKeepWarmEnabled').checked =
|
||||
session.keepWarm?.enabled ?? session.keepWarmEnabled ?? false;
|
||||
this.updateKeepWarmStatus(sessionId);
|
||||
// Git: the case'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,85 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* The Git tab: the case's last scheduled run, and which values its rows show. A case 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 case 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.
|
||||
*/
|
||||
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 case 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.
|
||||
const follows = session.gitFetchEnabled === undefined && session.gitFetchIntervalSeconds === undefined;
|
||||
const enabled = follows ? app.gitFetchEnabled === true : session.gitFetchEnabled ?? false;
|
||||
const interval = follows ? app.gitFetchIntervalSeconds ?? 300 : session.gitFetchIntervalSeconds ?? 300;
|
||||
|
||||
followBox.checked = follows;
|
||||
box.checked = enabled;
|
||||
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 case follows the app setting.' : 'Nothing fetched on a timer yet for this case.'];
|
||||
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;
|
||||
// `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(document.getElementById('modalGitFetchInterval').value, 10) || 300)
|
||||
),
|
||||
};
|
||||
try {
|
||||
const data = await this._apiPost(`/api/sessions/${this.editingSessionId}/git-fetch-settings`, body);
|
||||
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 +3248,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.
|
||||
|
||||
@@ -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
|
||||
@@ -2948,6 +2953,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,
|
||||
|
||||
@@ -7151,6 +7151,33 @@ html[data-skin="og"] .welcome-primary:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
/* 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). */
|
||||
.btn-icon-sm[disabled] {
|
||||
color: var(--text-dim);
|
||||
opacity: 0.45;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.btn-icon-sm[disabled]:hover {
|
||||
background: none;
|
||||
}
|
||||
|
||||
.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;
|
||||
}
|
||||
}
|
||||
|
||||
.settings-section {
|
||||
margin-bottom: 1.25rem;
|
||||
padding-bottom: 1rem;
|
||||
@@ -22167,7 +22194,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 +22204,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;
|
||||
|
||||
@@ -1,18 +1,22 @@
|
||||
/**
|
||||
* @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, fetchGitWorkspaceOverview, type GitFetchReport } from '../../git-fetch.js';
|
||||
import { readDockerCases } from '../../docker-hosts.js';
|
||||
import { getDataDir } from '../../config/instance.js';
|
||||
import { findSessionOrFail } from '../route-helpers.js';
|
||||
@@ -30,8 +34,12 @@ import {
|
||||
} from '../../git-workspace-status.js';
|
||||
import type { 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);
|
||||
|
||||
/**
|
||||
@@ -119,4 +127,27 @@ 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 Codeman runs
|
||||
// that writes, and it writes remote-tracking refs only — nothing commits, checks out or merges, so an
|
||||
// agent working in the same repository is not disturbed. Remote and Docker sessions answer `unsupported`
|
||||
// like the status route, and a repository a container can write to is refused before any git runs.
|
||||
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' }) };
|
||||
return {
|
||||
success: true,
|
||||
data: await fetchGitWorkspaceOverview(session.workingDir, {
|
||||
git,
|
||||
...limits,
|
||||
dockerWorkspaces: await dockerWorkspaces(),
|
||||
}),
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -57,6 +57,7 @@ import {
|
||||
AutoCompactSchema,
|
||||
AutoResumeSchema,
|
||||
KeepWarmSchema,
|
||||
GitFetchSettingsSchema,
|
||||
PinSessionSchema,
|
||||
ImageWatcherSchema,
|
||||
FlickerFilterSchema,
|
||||
@@ -3608,6 +3609,38 @@ export function registerSessionRoutes(
|
||||
};
|
||||
});
|
||||
|
||||
// ========== Git fetch on an interval ==========
|
||||
|
||||
// Per-case override for the fetch interval (src/git-fetch-scheduler.ts). `null` on either field clears
|
||||
// the case'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) => {
|
||||
|
||||
@@ -1488,6 +1488,16 @@ 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 Codeman runs that writes, and the only
|
||||
* one that runs a repository's own hooks, so nothing runs on a timer until the user turns this on.
|
||||
* Cap in seconds between runs (30 to 3600, default 300). A case can override both in Session Options
|
||||
* → Git; `null` there clears the override.
|
||||
*/
|
||||
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 +1938,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(),
|
||||
|
||||
@@ -100,6 +100,7 @@ import { getLifecycleLog } from '../session-lifecycle-log.js';
|
||||
import {
|
||||
applyWorkspaceHooks,
|
||||
pruneAgentSessionPreambles,
|
||||
readGitFetchSettings,
|
||||
readKeepWarmSettingsOrThrow,
|
||||
readPlanUsageTelemetryEnabled,
|
||||
removeAgentSessionPreamble,
|
||||
@@ -123,6 +124,9 @@ 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 { fetchGitWorkspaceOverview } from '../git-fetch.js';
|
||||
import { GitFetchScheduler } from '../git-fetch-scheduler.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';
|
||||
@@ -293,6 +297,7 @@ import {
|
||||
STATS_COLLECTION_INTERVAL_MS,
|
||||
INACTIVITY_TIMEOUT_MS,
|
||||
CRON_TICK_INTERVAL,
|
||||
GIT_FETCH_TICK_INTERVAL_MS,
|
||||
} from '../config/server-timing.js';
|
||||
|
||||
/**
|
||||
@@ -389,6 +394,28 @@ 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,
|
||||
fetch: (cwd, opts) => fetchGitWorkspaceOverview(cwd, opts),
|
||||
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. Persisted, because what a run found is the panel's current truth.
|
||||
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
|
||||
@@ -1242,6 +1269,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);
|
||||
@@ -1499,6 +1541,9 @@ export class WebServer extends EventEmitter {
|
||||
): Promise<void> {
|
||||
const session = this.sessions.get(sessionId);
|
||||
this.keepWarmService.remove(sessionId);
|
||||
// A closed case 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 }], () =>
|
||||
@@ -3540,6 +3585,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.
|
||||
@@ -3762,6 +3810,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 case'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 case 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.
|
||||
@@ -4233,6 +4286,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();
|
||||
|
||||
@@ -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, {}])),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,308 @@
|
||||
/**
|
||||
* @fileoverview The Git fetch interval scheduler (src/git-fetch-scheduler.ts): which cases 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.
|
||||
*
|
||||
* 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 GitFetchReport,
|
||||
type GitFetchSettings,
|
||||
type GitFetchStatus,
|
||||
} from '../src/git-fetch.js';
|
||||
import { DEFAULT_GIT_TIMEOUT_MS, MAX_REPOS } from '../src/git-workspace-status.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(),
|
||||
});
|
||||
|
||||
type Harness = {
|
||||
scheduler: GitFetchScheduler;
|
||||
ports: GitFetchPorts;
|
||||
calls: Array<{ id: string; opts: unknown }>;
|
||||
published: Array<{ id: string; status: GitFetchStatus }>;
|
||||
settings: GitFetchSettings;
|
||||
dockerReads: number;
|
||||
};
|
||||
|
||||
/** 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?: (id: string) => Promise<GitFetchReport> } = {}
|
||||
): Harness {
|
||||
const customFetch = opts.fetch;
|
||||
const settings = opts.settings ?? { ...SETTINGS };
|
||||
const h: Harness = {
|
||||
scheduler: undefined as unknown as GitFetchScheduler,
|
||||
ports: undefined as unknown as GitFetchPorts,
|
||||
calls: [],
|
||||
published: [],
|
||||
settings,
|
||||
dockerReads: 0,
|
||||
};
|
||||
h.ports = {
|
||||
sessionIds: () => sessions.map((s) => s.id),
|
||||
getSession: (id) => 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 [];
|
||||
},
|
||||
fetch: async (cwd, portOpts) => {
|
||||
const id = cwd.slice(3); // the '/w/<id>' the view was built with
|
||||
h.calls.push({ id, opts: portOpts });
|
||||
return customFetch ? customFetch(id) : report(cwd, id);
|
||||
},
|
||||
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 Docker case list is only worth reading once something is actually due.
|
||||
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 case is still due at once.
|
||||
expect(await h.scheduler.tick(1000)).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('who runs', () => {
|
||||
it('runs every case 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.id).sort()).toEqual(['a', '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 case that turned itself on even while the app-wide switch is off — that is what a per-case 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.id)).toEqual(['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 case, 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.id)).toEqual(['local']);
|
||||
});
|
||||
|
||||
it('re-checks the Docker rule every tick, so a case that 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 run at a time', () => {
|
||||
it('skips a case still being fetched instead of stacking runs on it', async () => {
|
||||
const gate = deferred<GitFetchReport>(report('/w/a', 'a'));
|
||||
const h = harness([VIEW('a')], { settings: { enabled: true, intervalSeconds: 30 }, fetch: () => gate.promise });
|
||||
const running = h.scheduler.tick(0);
|
||||
await new Promise((resolve) => setImmediate(resolve)); // the run has started, and is still held open
|
||||
expect(await h.scheduler.tick(15_000)).toBe(0);
|
||||
expect(h.calls.length).toBe(1);
|
||||
gate.resolve(report('/w/a', 'a'));
|
||||
await running;
|
||||
});
|
||||
|
||||
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<GitFetchReport>(report('/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 case is already past due: the
|
||||
// next tick runs it again instead of waiting another 30 s from when the slow one finished.
|
||||
slow.resolve(report('/w/a', 'a'));
|
||||
await first;
|
||||
expect(await h.scheduler.tick(200_000)).toBe(1);
|
||||
expect(h.calls.length).toBe(2);
|
||||
});
|
||||
|
||||
it('runs at most FETCH_CONCURRENCY cases at a time, because each one is a git process', async () => {
|
||||
const ids = Array.from({ length: FETCH_CONCURRENCY + 3 }, (_, i) => `s${i}`);
|
||||
let live = 0;
|
||||
let peak = 0;
|
||||
const h = harness(
|
||||
ids.map((id) => VIEW(id)),
|
||||
{
|
||||
fetch: async () => {
|
||||
live++;
|
||||
peak = Math.max(peak, live);
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
live--;
|
||||
return report('/w/x', 'x');
|
||||
},
|
||||
}
|
||||
);
|
||||
await h.scheduler.tick(0);
|
||||
expect(peak).toBe(FETCH_CONCURRENCY);
|
||||
expect(h.calls.length).toBe(ids.length);
|
||||
});
|
||||
});
|
||||
|
||||
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("reports a failure instead of retrying harder, and keeps the case's own 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 case'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 case that goes away', () => {
|
||||
it('takes its schedule with it, so a reopened case starts on its own clock', async () => {
|
||||
const h = harness([VIEW('a')]);
|
||||
await h.scheduler.tick(0);
|
||||
expect(h.scheduler.tracked()).toBe(1);
|
||||
|
||||
h.scheduler.remove('a');
|
||||
expect(h.scheduler.tracked()).toBe(0);
|
||||
await h.scheduler.tick(1000);
|
||||
expect(h.calls.length).toBe(2); // remembered again, from now
|
||||
});
|
||||
|
||||
it('stops everything after stop(), including a case 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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,349 @@
|
||||
/**
|
||||
* @fileoverview Tests for the Git panel's Fetch button (src/git-fetch.ts): the one git command Codeman
|
||||
* runs that writes, and the one that runs a repository's own hooks — which is why it is a click, not a poll.
|
||||
*
|
||||
* Two halves, mirroring the module:
|
||||
*
|
||||
* 1. The PURE half — the fixed argv, 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.
|
||||
*
|
||||
* Port: N/A (no server).
|
||||
*/
|
||||
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
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,
|
||||
buildFetchArgs,
|
||||
describeFetchFailure,
|
||||
fetchGitWorkspaceOverview,
|
||||
gitFetchSettingsFrom,
|
||||
gitFetchStatusFrom,
|
||||
type GitFetchReport,
|
||||
} from '../src/git-fetch.js';
|
||||
import { 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();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── 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([]);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
|
||||
@@ -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[] = [];
|
||||
|
||||
@@ -353,6 +353,177 @@ 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('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();
|
||||
});
|
||||
});
|
||||
@@ -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,33 @@ 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 case, and hides it for the ones nothing is ever fetched for', () => {
|
||||
const modal = optionsModal();
|
||||
// A shell case 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 cases 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 case 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 case 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.
|
||||
expect(methodBody('async autoSaveGitFetch()')).toContain('{ enabled: null, intervalSeconds: null }');
|
||||
// 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"');
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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 状态']);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user