mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-16 19:29:33 +01:00
fix: apply the review items for #714 at merge
- Session update no longer resets "How often" while typing: updateGitFetchStatus (session-ui.js) leaves a control alone while it is document.activeElement, and autoSaveGitFetch writes the clamped interval back itself (Enter saves with the field still focused). - Partial override shows the app values: enabled = session ?? app switch, interval = session ?? app interval ?? 300 (session-ui.js updateGitFetchStatus). - runFetch (git-fetch.ts) arms the spawn with what the core.sshCommand read left of timeoutMs, and answers ETIMEDOUT without spawning when nothing is left, so a git that never answers costs one timeout, not two. - fetchEnvFor keeps a GIT_SSH from the server's environment (repoSshCommand || base.GIT_SSH), fileoverview and CLAUDE.md line updated to say so. - i18n.js: the zh-CN "Git fetch on an interval" description scopes the only writing git command to the Git window. - styles.css: the disabled/busy rules are scoped to .git-status-actions .btn-icon-sm (moved beside .git-status-actions), and the busy pulse stops under prefers-reduced-motion. - Comments that called the override per case now say per session: session.ts (field, restore and getter docs, setGitFetchSettings), git-fetch-scheduler.ts:2, server-timing.ts:78, server.ts (cleanup and restore), app.js _onSessionUpdated, session-ui.js (openSessionOptions and updateGitFetchStatus). - Tests: test/git-fetch-session-options-ui.test.ts (new, JSDOM: typing survives an SSE update, the Enter write-back, both partial cases); test/git-fetch.test.ts (GIT_SSH kept; one bound for the read and the fetch, stub git on PATH). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3411d7f35a
commit
6539bc6c82
12 files changed
+299
-68
No files matched your search
@@ -236,7 +236,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
|
||||
**Git status indicator** (`showGitStatus`, per-device, default OFF; `src/git-workspace-status.ts`, `routes/git-status-routes.ts`, `git-status-ui.js`): the bottom-bar indicator and its panel read `GET /api/sessions/:id/git-status` and `/git-diff`, read-only and offline on its own (it never fetches; fetching is the separate path below). ⚠️ git never runs on a repository at or inside a Docker case workspace (walk-up, scan and diff alike, and a cached repository list is re-checked against the CURRENT Docker roots), since a container could plant a clean filter that runs on the host; remote and Docker sessions answer `unsupported`. ⚠️ `git-diff` takes `repo`/`path`/`kind` only as keys matched against the workspace's own repository list (`findWorkspaceRepo()`) and that repository's current status, never as paths. ⚠️ Keep `--no-optional-locks`, `core.fsmonitor=false` and `log.showSignature=false` on every call and `--no-ext-diff --no-textconv` on diffs; clean filters still run, which is why the Docker rule exists. ⚠️ An enclosing repository at `$HOME` or above is ignored (`isUnrelatedAncestor()`), and is identified by one cached `rev-parse` before any full status runs. Everything git supplies renders via `textContent`. Tests: `test/git-workspace-status.test.ts`, `test/routes/git-status-routes.test.ts`, and `test/git-status.browser.test.ts` (browser suite, not in the gate).
|
||||
|
||||
**Git fetch** (`src/git-fetch.ts`, `src/git-fetch-scheduler.ts`, `routes/git-status-routes.ts`, the panel's **Fetch** button): `POST /api/sessions/:id/git-fetch` is the ONLY git command the Git PANEL runs that WRITES — cloning and worktree management write too, but only when the user asked for them at that moment — and it is the only one that can run later by itself, on a timer, and the only one that can run a repository's own hooks (`reference-transaction`, `pre-auto-gc` through the automatic maintenance a fetch triggers, config commands such as `credential.helper`) — which is why it is opt-in and never runs on a timer until the user turns it on. ⚠️ Fetch updates remote-tracking refs only; it must never commit, check out, merge or touch the working tree. ⚠️ It is not as harmless as a read: a fetch holds git's ref lock, so an agent's own `git pull` in the same clone can hit the same `cannot lock ref` — hence one folder is fetched by at most one run at a time (`fetchWorkspaceOnce` joins a run already going), and `FETCH_CONFIG_ARGS` (`-c core.fsmonitor=false -c maintenance.auto=false -c gc.auto=0`) keeps an unattended fetch from starting a gc in a repository the agent is using. ⚠️ `buildFetchArgs()` is `['fetch', '--quiet']` and must stay verb-invariant (`test/git-fetch.test.ts`); those `-c` overrides are added by the runner, not by `buildFetchArgs()`. ⚠️ The git timeout must reach the whole process TREE, not just the `git` parent: `execFile` signals the parent only, so `runFetch` spawns `detached` and signals the negative pid (SIGTERM, then SIGKILL `FETCH_KILL_ESCALATION_MS` later), and the caller is answered AT the timeout while the group is still dying — that is the point. `test/git-fetch.test.ts` proves it against a local server that never answers, by group membership rather than parentage. A non-zero exit must still reject the way `execFile` would, or a real failure reads as a clean run with no reason. ⚠️ The same Docker rule as above applies BEFORE any git runs (a repository at or inside a Docker case workspace is refused), and remote sessions answer `unsupported`. ⚠️ Keep it non-interactive (`gitNonInteractiveEnv()`: `GIT_TERMINAL_PROMPT=0` + BatchMode ssh) or a fetch hangs on an invisible login prompt — but that BatchMode ssh is a DEFAULT, never an override: `fetchEnvFor` must not overwrite the repository's `core.sshCommand` or the user's own `GIT_SSH_COMMAND` (`readRepoSshCommand` reads it inside the same limiter slot and the same wall-clock bound as the fetch it serves), and `StrictHostKeyChecking=accept-new` writes an unknown host key into `~/.ssh/known_hosts` without asking — BatchMode stops a prompt, not a write. Keep it bounded: `MAX_REPOS`/`MAX_REPOS_LIMIT` (12/50), `MAX_FETCH_OUTPUT_BYTES` (2 MB), the git timeout per spawn, and `FETCH_CONCURRENCY` (4) as ONE `Limiter` shared by the fetches of the whole tick — `createLimiter` keeps its count in the closure, so a limiter that delegated to `mapLimited` per call bounds each call, and 4 folders × 4 repositories would start 16 git processes. ⚠️ One semaphore cannot bound both the folders and the fetches: a folder holding a slot would then wait for a slot its own fetch needs, so the tick bounds its folders with `mapLimited` and hands the shared bound to every run. ⚠️ Failure text reaching a client is control-stripped and credential-redacted (`sanitizeGitOutput`) and the browser writes it with `textContent`. Scheduler semantics: settings are read fresh each tick (`GIT_FETCH_TICK_INTERVAL_MS`, 15 s), a per-session override wins even while the app-wide switch is off, the interval is timed from the run START, state is keyed by FOLDER (sessions sharing one folder are the same clone, so one run serves them all, the schedule is stamped at selection, and every session on a folder is remembered, a folder is due when ANY session open on it is due — so the order the sessions were read cannot decide which interval wins (both orders are tested) — and the folder is probed once for the whole group rather than once per session on it — closing the one that holds the override must not stop the folder's fetching while another session is still open on it), a tick is skipped while the previous one is still going, and a user-chosen folder is probed BOUNDED with the default options before anything runs (rule #516 — `unknown` is never read as `absent`). ⚠️ The two settings (`gitFetchEnabled`, `gitFetchIntervalSeconds`, off/300 by default, clamped 30–3600) are **synced**, not per-device: they must stay out of `displayKeys` and out of the strip destructure in settings-ui.js, or the scheduler reads nobody's value. Per-session state rides `SessionUpdated` (no new SSE event) as `gitFetch`, and the click route publishes the run's trigger, not the request's: `trigger: 'click'` only when the click was the run, because a click that joined a tick already going fetched nothing and cannot report itself as the fetch (`GitFeLine truncated
|
||||
**Git fetch** (`src/git-fetch.ts`, `src/git-fetch-scheduler.ts`, `routes/git-status-routes.ts`, the panel's **Fetch** button): `POST /api/sessions/:id/git-fetch` is the ONLY git command the Git PANEL runs that WRITES — cloning and worktree management write too, but only when the user asked for them at that moment — and it is the only one that can run later by itself, on a timer, and the only one that can run a repository's own hooks (`reference-transaction`, `pre-auto-gc` through the automatic maintenance a fetch triggers, config commands such as `credential.helper`) — which is why it is opt-in and never runs on a timer until the user turns it on. ⚠️ Fetch updates remote-tracking refs only; it must never commit, check out, merge or touch the working tree. ⚠️ It is not as harmless as a read: a fetch holds git's ref lock, so an agent's own `git pull` in the same clone can hit the same `cannot lock ref` — hence one folder is fetched by at most one run at a time (`fetchWorkspaceOnce` joins a run already going), and `FETCH_CONFIG_ARGS` (`-c core.fsmonitor=false -c maintenance.auto=false -c gc.auto=0`) keeps an unattended fetch from starting a gc in a repository the agent is using. ⚠️ `buildFetchArgs()` is `['fetch', '--quiet']` and must stay verb-invariant (`test/git-fetch.test.ts`); those `-c` overrides are added by the runner, not by `buildFetchArgs()`. ⚠️ The git timeout must reach the whole process TREE, not just the `git` parent: `execFile` signals the parent only, so `runFetch` spawns `detached` and signals the negative pid (SIGTERM, then SIGKILL `FETCH_KILL_ESCALATION_MS` later), and the caller is answered AT the timeout while the group is still dying — that is the point. `test/git-fetch.test.ts` proves it against a local server that never answers, by group membership rather than parentage. A non-zero exit must still reject the way `execFile` would, or a real failure reads as a clean run with no reason. ⚠️ The same Docker rule as above applies BEFORE any git runs (a repository at or inside a Docker case workspace is refused), and remote sessions answer `unsupported`. ⚠️ Keep it non-interactive (`gitNonInteractiveEnv()`: `GIT_TERMINAL_PROMPT=0` + BatchMode ssh) or a fetch hangs on an invisible login prompt — but that BatchMode ssh is a DEFAULT, never an override: `fetchEnvFor` must not overwrite the repository's `core.sshCommand`, the user's own `GIT_SSH_COMMAND` or a `GIT_SSH` (`readRepoSshCommand` reads it inside the same limiter slot and the same wall-clock bound as the fetch it serves, and the spawn gets only what the read left), and `StrictHostKeyChecking=accept-new` writes an unknown host key into `~/.ssh/known_hosts` without asking — BatchMode stops a prompt, not a write. Keep it bounded: `MAX_REPOS`/`MAX_REPOS_LIMIT` (12/50), `MAX_FETCH_OUTPUT_BYTES` (2 MB), the git timeout per spawn, and `FETCH_CONCURRENCY` (4) as ONE `Limiter` shared by the fetches of the whole tick — `createLimiter` keeps its count in the closure, so a limiter that delegated to `mapLimited` per call bounds each call, and 4 folders × 4 repositories would start 16 git processes. ⚠️ One semaphore cannot bound both the folders and the fetches: a folder holding a slot would then wait for a slot its own fetch needs, so the tick bounds its folders with `mapLimited` and hands the shared bound to every run. ⚠️ Failure text reaching a client is control-stripped and credential-redacted (`sanitizeGitOutput`) and the browser writes it with `textContent`. Scheduler semantics: settings are read fresh each tick (`GIT_FETCH_TICK_INTERVAL_MS`, 15 s), a per-session override wins even while the app-wide switch is off, the interval is timed from the run START, state is keyed by FOLDER (sessions sharing one folder are the same clone, so one run serves them all, the schedule is stamped at selection, and every session on a folder is remembered, a folder is due when ANY session open on it is due — so the order the sessions were read cannot decide which interval wins (both orders are tested) — and the folder is probed once for the whole group rather than once per session on it — closing the one that holds the override must not stop the folder's fetching while another session is still open on it), a tick is skipped while the previous one is still going, and a user-chosen folder is probed BOUNDED with the default options before anything runs (rule #516 — `unknown` is never read as `absent`). ⚠️ The two settings (`gitFetchEnabled`, `gitFetchIntervalSeconds`, off/300 by default, clamped 30–3600) are **synced**, not per-device: they must stay out of `displayKeys` and out of the strip destructure in settings-ui.js, or the scheduler reads nobody's value. Per-session state rides `SessionUpdated` (no new SSE event) as `gitFetch`, and the click route publishes the run's trigger, not the request's: `trigger: 'click'` only when the click was the run, because a click that joined a tick already going fetcLine truncated
|
||||
|
||||
**Raw file bodies are streamed and range-aware**: `file-raw`, the attachments `/raw` route, `GET /api/download` and the rendered-HTML route `GET /html-view/<cap>/...` share `sendFileBody()`, advertise `Accept-Ranges: bytes` and answer `Range` with `206` + `Content-Range` (single-range, parser in `src/web/http-range.ts`); without it `<video>` cannot seek. The size cap (`MAX_FILE_DOWNLOAD_BYTES`, default 2GB, env `CODEMAN_MAX_DOWNLOAD_BYTES`, `0` = unlimited) is a sanity bound, not memory protection; never reintroduce a whole-file buffer. ⚠️ Bodies go out via `reply.hijack()`, so `sendRawStream` must copy the status onto `reply.raw` by hand or a partial body ships as `200`. ⚠️ Closing the preview must pause and unload media (`_stopFilePreviewMedia`), since a detached `HTMLMediaElement` keeps playing. → [architecture-invariants#raw-file-bodies-streamed-and-range-aware](docs/architecture-invariants.md#raw-file-bodies-streamed-and-range-aware)
|
||||
|
||||
|
||||
@@ -75,7 +75,7 @@ export const ITERATION_PAUSE_MS = 2000;
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* How often the fetch scheduler (src/git-fetch-scheduler.ts) wakes to check which cases are due (ms). A
|
||||
* How often the fetch scheduler (src/git-fetch-scheduler.ts) wakes to check which sessions are due (ms). A
|
||||
* run lands within one tick of the interval the user set, because the interval is timed from the start of
|
||||
* a run; a tick is a settings read and a due check, not a spawn, so a quiet install costs nothing.
|
||||
*/
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* @fileoverview Git fetch on an interval: the cases the user turned on, fetched by a tick the server owns
|
||||
* @fileoverview Git fetch on an interval: the sessions the user turned on, fetched by a tick the server owns
|
||||
* (`src/git-fetch-scheduler.ts`, wired in `src/web/server.ts`).
|
||||
*
|
||||
* The fetch module (src/git-fetch.ts) is the only git command the Git panel runs that writes, and on a timer
|
||||
|
||||
+25
-9
@@ -35,9 +35,9 @@
|
||||
* login fails fast instead of hanging the request on an invisible username prompt. Codeman collects
|
||||
* no credentials; a repository the user's own git is already signed in to works because that is the
|
||||
* user's existing setup, so unlike a clone no credential helper is disabled here. That BatchMode ssh is
|
||||
* a default, never an override: `fetchEnvFor` keeps whatever the repository's `core.sshCommand` or the
|
||||
* user's own `GIT_SSH_COMMAND` already says, because on a machine with several ssh setups that choice
|
||||
* is usually the one that works. ⚠️ The default still leaves a record: `StrictHostKeyChecking=accept-new`
|
||||
* a default, never an override: `fetchEnvFor` keeps whatever the repository's `core.sshCommand`, the
|
||||
* user's own `GIT_SSH_COMMAND` or a `GIT_SSH` already says, because on a machine with several ssh setups
|
||||
* that choice is usually the one that works. ⚠️ The default still leaves a record: `StrictHostKeyChecking=accept-new`
|
||||
* writes an unknown host key into `~/.ssh/known_hosts` without asking — BatchMode stops a prompt, not a
|
||||
* write.
|
||||
* - The timeout kills the PROCESS GROUP, not just the `git` parent. A fetch over http spawns
|
||||
@@ -180,15 +180,18 @@ export function describeFetchFailure(err: unknown): FetchFailure {
|
||||
* `gitNonInteractiveEnv` supplies the BatchMode default, and the default is only a default: git reads
|
||||
* `GIT_SSH_COMMAND` from the environment ahead of the repository's `core.sshCommand`, so setting it would
|
||||
* override a repository that already chose its own ssh — an alternative host, an identity file, a jump box —
|
||||
* and break a setup that works today. That is the only case where this module makes an ssh choice on the
|
||||
* user's behalf, so it is the whole decision here: the caller supplies the value it read, and this decides
|
||||
* between the user's environment and the repository's own answer.
|
||||
* and break a setup that works today. The server's own `GIT_SSH` is the same kind of answer: git reads it
|
||||
* after both of those (`GIT_SSH_COMMAND`, then `core.sshCommand`, then `GIT_SSH`), so a written default would
|
||||
* hide it too. That is the only case where this module makes an ssh choice on the user's behalf, so it is the
|
||||
* whole decision here: the caller supplies the value it read, and this decides between the user's
|
||||
* environment and the repository's own answer.
|
||||
*/
|
||||
export function fetchEnvFor(base: NodeJS.ProcessEnv, repoSshCommand: string | null): NodeJS.ProcessEnv {
|
||||
const env = gitNonInteractiveEnv(base);
|
||||
// `gitNonInteractiveEnv` only writes the default when the environment had nothing, so this is exactly the
|
||||
// case where it was a choice rather than a pass-through — and the repository's own answer wins over it.
|
||||
if (!base.GIT_SSH_COMMAND && repoSshCommand) delete env.GIT_SSH_COMMAND;
|
||||
// case where it was a choice rather than a pass-through, and the repository's own answer, or a `GIT_SSH` in
|
||||
// the environment, wins over it.
|
||||
if (!base.GIT_SSH_COMMAND && (repoSshCommand || base.GIT_SSH)) delete env.GIT_SSH_COMMAND;
|
||||
return env;
|
||||
}
|
||||
|
||||
@@ -231,10 +234,23 @@ export async function readRepoSshCommand(cwd: string, timeoutMs: number): Promis
|
||||
* spawn failure (`spawn git ENOENT` → GIT_MISSING), `killed` and `code` for the timeout. A non-zero exit
|
||||
* rejects the way `execFile` would — `code` is then the exit code — because resolving it would report a real
|
||||
* failure as a clean run with an empty reason.
|
||||
*
|
||||
* `timeoutMs` bounds the `core.sshCommand` read and the fetch TOGETHER: the spawn is armed with what the read
|
||||
* left, so a `git` that never answers costs one timeout, not two. A read that used the whole bound answers
|
||||
* as a timeout without starting the fetch.
|
||||
*/
|
||||
export const runFetch: GitRunner = async (cwd, args, opts) => {
|
||||
const timeoutMs = opts?.timeoutMs ?? DEFAULT_GIT_TIMEOUT_MS;
|
||||
const startedAt = Date.now();
|
||||
const env = fetchEnvFor(process.env, await readRepoSshCommand(cwd, timeoutMs));
|
||||
const remainingMs = timeoutMs - (Date.now() - startedAt);
|
||||
if (remainingMs <= 0) {
|
||||
throw Object.assign(new Error(`Command failed: git ${args.join(' ')}`), {
|
||||
stderr: '',
|
||||
killed: true,
|
||||
code: 'ETIMEDOUT',
|
||||
});
|
||||
}
|
||||
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
let child: ReturnType<typeof spawn>;
|
||||
@@ -289,7 +305,7 @@ export const runFetch: GitRunner = async (cwd, args, opts) => {
|
||||
killTree('SIGTERM');
|
||||
killTimer = setTimeout(() => killTree('SIGKILL'), FETCH_KILL_ESCALATION_MS);
|
||||
fail();
|
||||
}, timeoutMs);
|
||||
}, remainingMs);
|
||||
|
||||
child.stdout?.on('data', (chunk: Buffer) => {
|
||||
stdoutBytes += chunk.length;
|
||||
|
||||
+7
-7
@@ -615,9 +615,9 @@ 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. */
|
||||
/** Git fetch on an interval for this session; 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. */
|
||||
/** Seconds between this session's fetch runs; undefined = follow the app-wide default. Persisted. */
|
||||
private _gitFetchIntervalSeconds: number | undefined;
|
||||
/** Last status the fetch scheduler published for this session; ephemeral. */
|
||||
private _gitFetch: GitFetchStatus | null = null;
|
||||
@@ -933,9 +933,9 @@ 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`). */
|
||||
/** Restored Git fetch override for this session (see `gitFetchEnabled`). */
|
||||
gitFetchEnabled?: boolean;
|
||||
/** Restored Git fetch interval for this case (see `gitFetchIntervalSeconds`). */
|
||||
/** Restored Git fetch interval for this session (see `gitFetchIntervalSeconds`). */
|
||||
gitFetchIntervalSeconds?: number;
|
||||
/** Restored conversation chain, oldest first (see `claudeSessionChain`). */
|
||||
claudeSessionChain?: string[];
|
||||
@@ -1594,18 +1594,18 @@ export class Session extends EventEmitter {
|
||||
return changed;
|
||||
}
|
||||
|
||||
/** Git fetch override for this case; undefined means the app-wide setting applies. */
|
||||
/** Git fetch override for this session; 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. */
|
||||
/** Interval override for this session; 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
|
||||
* Set the session's override. The Session Options rows save on their own, so a caller passes what it has
|
||||
* and leaves the other half as it was; `undefined` on either means the app-wide setting applies again.
|
||||
*/
|
||||
setGitFetchSettings(enabled: boolean | undefined, intervalSeconds: number | undefined): void {
|
||||
|
||||
@@ -2455,8 +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).
|
||||
// A scheduled fetch publishes the session's result on this same event, so an open Session Options modal
|
||||
// on that session shows it without polling its own (session-ui.js: updateGitFetchStatus, which leaves the
|
||||
// control being typed in alone).
|
||||
if (this.editingSessionId === session.id) this.updateGitFetchStatus(session.id);
|
||||
// If claudeSessionId was just set, re-check orphan subagents
|
||||
// This connects subagents that were waiting for the session to identify itself
|
||||
|
||||
@@ -538,7 +538,7 @@
|
||||
'单条 git 命令可运行的秒数,超时后该仓库会被报告为无法读取(5 到 120,默认 30)。仓库位于较慢的网络共享上时请调高此值。',
|
||||
'Git fetch on an interval': 'Git 定时拉取',
|
||||
'Runs `git fetch` for the repositories the Git window lists on a timer, so the "behind" number is current without a click. Off by default: this is the only git command the Git panel runs that writes, and the only one Codeman runs on a timer (cloning and worktree management write too, but only when you asked for them at the moment you asked), so nothing runs until you turn it on. A session can override both the switch and the interval in Session Options → Git.':
|
||||
'按间隔为 Git 窗口列出的仓库运行拉取,这样“落后”的数字无需点击就是最新的。默认关闭:这是 {name} 运行的唯一会写入的 git 命令,也是唯一会按间隔自行运行的命令(克隆和工作树管理也会写入,但只在您当时要求时才运行),所以在您开启之前不会有任何运行。会话可以在“会话选项 → Git”中同时覆盖开关和间隔。',
|
||||
'按间隔为 Git 窗口列出的仓库运行拉取,这样“落后”的数字无需点击就是最新的。默认关闭:这是 Git 窗口运行的唯一会写入的 git 命令,也是 {name} 唯一会按间隔自行运行的命令(克隆和工作树管理也会写入,但只在您当时要求时才运行),所以在您开启之前不会有任何运行。会话可以在“会话选项 → Git”中同时覆盖开关和间隔。',
|
||||
'Git fetch: how often': 'Git 定时拉取:多久一次',
|
||||
'Seconds between runs for a session that has no override of its own (30 to 3600, default 300). Only a session that is on — here, or in Session Options → Git — is fetched, and sessions sharing one folder are fetched by one run.':
|
||||
'没有自己覆盖设置的会话,两次运行之间的秒数(30 到 3600,默认 300)。只有已开启的会话——这里,或在“会话选项 → Git”——才会被拉取,共用一个文件夹的会话由一次运行拉取。',
|
||||
|
||||
@@ -2685,7 +2685,7 @@ 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
|
||||
// Git: the session's own choice if it has one, otherwise the app setting. updateGitFetchStatus is also
|
||||
// what SSE calls when a scheduled run lands, so the rows stay current while the modal is open.
|
||||
this.updateGitFetchStatus(sessionId);
|
||||
document.getElementById('modalImageWatcherEnabled').checked = session.imageWatcherEnabled ?? true;
|
||||
@@ -3032,11 +3032,15 @@ 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
|
||||
* The Git tab: the session's last scheduled run, and which values its rows show. A session with no choice of
|
||||
* its own follows the app setting, so its switch and interval display the app's numbers and go inert (the
|
||||
* same inert-row pattern as updateKeepWarmStatus above), because changing them here is what makes the session
|
||||
* stop following. The app numbers come from the settings cache, so what this shows can be one settings load
|
||||
* behind; the server decides from a fresh read, not from what the page displays.
|
||||
*
|
||||
* SSE calls this on every `session:updated` for the open session (app.js `_onSessionUpdated`), and a working
|
||||
* session sends one on each working/idle change, so a control the user is in (`document.activeElement`) is
|
||||
* left as it is: rewriting it put a half-typed interval back to the stored one before `onchange` could save it.
|
||||
*/
|
||||
updateGitFetchStatus(sessionId) {
|
||||
const statusEl = document.getElementById('gitFetchStatus');
|
||||
@@ -3048,15 +3052,17 @@ Object.assign(CodemanApp.prototype, {
|
||||
if (!session) return;
|
||||
|
||||
const app = this.loadAppSettingsFromStorage() || {};
|
||||
// No choice of its own on either field means the session follows the app. A partial one — its own switch,
|
||||
// the app's interval — means it does not, and the row that still follows shows the app's value.
|
||||
// No choice of its own on either field means the session follows the app. A partial one (its own switch,
|
||||
// the app's interval) means it does not, and the row that still follows shows the app's value, which is
|
||||
// also the value the scheduler runs it with (a default here would show one number and fetch at another).
|
||||
const follows = session.gitFetchEnabled === undefined && session.gitFetchIntervalSeconds === undefined;
|
||||
const enabled = follows ? app.gitFetchEnabled === true : session.gitFetchEnabled ?? false;
|
||||
const interval = follows ? app.gitFetchIntervalSeconds ?? 300 : session.gitFetchIntervalSeconds ?? 300;
|
||||
const enabled = session.gitFetchEnabled ?? (app.gitFetchEnabled === true);
|
||||
const interval = session.gitFetchIntervalSeconds ?? app.gitFetchIntervalSeconds ?? 300;
|
||||
|
||||
followBox.checked = follows;
|
||||
box.checked = enabled;
|
||||
num.value = interval;
|
||||
const focused = document.activeElement;
|
||||
if (followBox !== focused) followBox.checked = follows;
|
||||
if (box !== focused) box.checked = enabled;
|
||||
if (num !== focused) num.value = interval;
|
||||
for (const el of [box, num]) {
|
||||
el.closest('.set-row')?.classList.toggle('set-row-disabled', follows);
|
||||
el.disabled = follows;
|
||||
@@ -3085,16 +3091,17 @@ Object.assign(CodemanApp.prototype, {
|
||||
async autoSaveGitFetch() {
|
||||
if (!this.editingSessionId) return;
|
||||
const follow = document.getElementById('modalGitFetchFollow').checked;
|
||||
const num = document.getElementById('modalGitFetchInterval');
|
||||
// `null` on the route means "no choice of your own", which is what following the app setting is.
|
||||
const body = follow
|
||||
? { enabled: null, intervalSeconds: null }
|
||||
: {
|
||||
enabled: document.getElementById('modalGitFetchEnabled').checked,
|
||||
intervalSeconds: Math.min(
|
||||
3600,
|
||||
Math.max(30, parseInt(document.getElementById('modalGitFetchInterval').value, 10) || 300)
|
||||
),
|
||||
intervalSeconds: Math.min(3600, Math.max(30, parseInt(num.value, 10) || 300)),
|
||||
};
|
||||
// Enter fires `onchange` with the field still focused, and updateGitFetchStatus leaves a focused field
|
||||
// alone, so the clamped number is written back here or the field would keep showing what was typed.
|
||||
if (!follow) num.value = body.intervalSeconds;
|
||||
try {
|
||||
// `_apiPost` hands back the Response without checking it, so a refused body (a 400) still read as a
|
||||
// save. `_apiJson` is the one that says whether the call went through, and null here means it did not.
|
||||
|
||||
+36
-27
@@ -7151,33 +7151,6 @@ 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;
|
||||
@@ -22175,6 +22148,42 @@ html .toolbar .btn-git-status[aria-expanded='true'] {
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
/* A Fetch button cannot be clicked twice while its fetch is running, and is not offered for a session
|
||||
there is nothing to fetch for (no repository, remote or Docker). Scoped to the Git panel's header: the
|
||||
File Viewer's Back/Forward and the folder grid's Up button are .btn-icon-sm too, and keep their own look. */
|
||||
.git-status-actions .btn-icon-sm[disabled] {
|
||||
color: var(--text-dim);
|
||||
opacity: 0.45;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.git-status-actions .btn-icon-sm[disabled]:hover {
|
||||
background: none;
|
||||
}
|
||||
|
||||
.git-status-actions .btn-icon-sm[aria-busy='true'] {
|
||||
color: var(--text);
|
||||
animation: btn-icon-busy 1.1s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes btn-icon-busy {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 0.55;
|
||||
}
|
||||
50% {
|
||||
opacity: 0.9;
|
||||
}
|
||||
}
|
||||
|
||||
/* No pulse under reduced motion: the button holds the pulse's brighter step, still dimmer than at rest. */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.git-status-actions .btn-icon-sm[aria-busy='true'] {
|
||||
animation: none;
|
||||
opacity: 0.7;
|
||||
}
|
||||
}
|
||||
|
||||
.git-status-body {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
|
||||
+3
-3
@@ -1550,7 +1550,7 @@ 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
|
||||
// A closed session takes its place in the fetch schedule with it: otherwise a detached-and-forgotten id
|
||||
// would still count as tracked, and its next run would land on a session that no longer exists.
|
||||
this.gitFetchScheduler.remove(sessionId);
|
||||
const pinned = session?.pinned === true || this.store.getSession(sessionId)?.pinned === true;
|
||||
@@ -3819,9 +3819,9 @@ 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 session's own fetch switch and interval, carried over rather than reset to the app default:
|
||||
// the choice is the user's and outlives the run that made it. The scheduler reads them fresh
|
||||
// on its next tick, so a restored case is back on its own schedule without a restart.
|
||||
// on its next tick, so a restored session is back on its own schedule without a restart.
|
||||
gitFetchEnabled: savedState?.gitFetchEnabled,
|
||||
gitFetchIntervalSeconds: savedState?.gitFetchIntervalSeconds,
|
||||
// Conversations this pane provably owned, oldest first. Its tail is
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* @fileoverview The Session Options → Git rows (session-ui.js `updateGitFetchStatus`) as the page drives them: the
|
||||
* real index.html in JSDOM with the real app.js and session-ui.js loaded into it, and every session update
|
||||
* delivered through app.js `_onSessionUpdated`, the path a `session:updated` SSE event takes.
|
||||
*
|
||||
* 1. A working session sends `session:updated` on each working/idle change, and that path refreshes the open Git
|
||||
* tab every time, so the control the user is in is left alone: rewriting it put a half-typed "12" back to "300"
|
||||
* before `onchange` could save it. Enter saves with the field still focused, so the save writes the clamped
|
||||
* number back itself.
|
||||
* 2. The route takes one field at a time, so a session can hold half an override. The half it did not choose
|
||||
* shows the app's value, which is what the scheduler runs it with, never a default.
|
||||
*
|
||||
* Port: N/A (no server; the one save is answered by a stub).
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const PUBLIC = resolve(import.meta.dirname, '../src/web/public');
|
||||
const SID = 'session-git-rows';
|
||||
/** The app setting every case here runs against: on, every 900 s. */
|
||||
const APP = { gitFetchEnabled: true, gitFetchIntervalSeconds: 900 };
|
||||
|
||||
type Update = Record<string, unknown> & { id: string };
|
||||
type TestApp = Record<string, unknown> & {
|
||||
_onSessionUpdated(data: Update): void;
|
||||
autoSaveGitFetch(): Promise<void>;
|
||||
_apiJson: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
let dom: JSDOM;
|
||||
let CodemanApp: { prototype: object };
|
||||
|
||||
beforeAll(async () => {
|
||||
dom = new JSDOM(readFileSync(resolve(PUBLIC, 'index.html'), 'utf8'), {
|
||||
runScripts: 'outside-only',
|
||||
url: 'http://localhost/',
|
||||
});
|
||||
// app.js starts the app on DOMContentLoaded. Loading it once the document is complete means that never fires
|
||||
// here, so the real constructor (SSE, WebSocket, timers) never runs in a window with no server behind it.
|
||||
await new Promise<void>((done) =>
|
||||
dom.window.document.readyState === 'complete' ? done() : dom.window.addEventListener('load', () => done())
|
||||
);
|
||||
const context = dom.getInternalVMContext();
|
||||
// app.js's last line publishes MobileDetection (mobile-handlers.js), which nothing here otherwise needs.
|
||||
vm.runInContext('var MobileDetection = { isTouchDevice: () => false };', context);
|
||||
for (const file of ['constants.js', 'app.js', 'session-ui.js']) {
|
||||
vm.runInContext(readFileSync(resolve(PUBLIC, file), 'utf8'), context, { filename: file });
|
||||
}
|
||||
CodemanApp = vm.runInContext('CodemanApp', context);
|
||||
});
|
||||
|
||||
afterAll(() => dom.window.close());
|
||||
|
||||
beforeEach(() => {
|
||||
(dom.window.document.activeElement as HTMLElement | null)?.blur?.();
|
||||
});
|
||||
|
||||
const el = <T extends HTMLElement = HTMLInputElement>(id: string) => dom.window.document.getElementById(id) as T;
|
||||
|
||||
/** An app with the Git tab open on SID and everything the update path draws besides it stubbed. */
|
||||
function openGitTab(): TestApp {
|
||||
const app = Object.create(CodemanApp.prototype) as TestApp;
|
||||
Object.assign(app, {
|
||||
sessions: new Map(),
|
||||
_closingSessions: new Set(),
|
||||
activeSessionId: null,
|
||||
editingSessionId: SID,
|
||||
renderSessionTabs: vi.fn(),
|
||||
updateCost: vi.fn(),
|
||||
updateSubagentParentNames: vi.fn(),
|
||||
showToast: vi.fn(),
|
||||
loadAppSettingsFromStorage: () => ({ ...APP }),
|
||||
});
|
||||
return app;
|
||||
}
|
||||
|
||||
describe('Session Options → Git, under session updates', () => {
|
||||
it('leaves the interval the user is typing alone when a session update arrives, and still refreshes the run line', () => {
|
||||
const app = openGitTab();
|
||||
app._onSessionUpdated({ id: SID, status: 'idle', gitFetchEnabled: true, gitFetchIntervalSeconds: 300 });
|
||||
const num = el('modalGitFetchInterval');
|
||||
expect(num.disabled).toBe(false);
|
||||
expect(num.value).toBe('300');
|
||||
|
||||
num.focus();
|
||||
expect(dom.window.document.activeElement).toBe(num);
|
||||
num.value = '12';
|
||||
// The working/idle flip that used to put the field back to 300, carrying a scheduled run's result this time.
|
||||
app._onSessionUpdated({
|
||||
id: SID,
|
||||
status: 'busy',
|
||||
gitFetchEnabled: true,
|
||||
gitFetchIntervalSeconds: 300,
|
||||
gitFetch: { ranAt: Date.now(), trigger: 'interval', state: 'ok', repos: 2, failed: 0 },
|
||||
});
|
||||
expect(num.value).toBe('12');
|
||||
expect(el('gitFetchStatus').textContent).toBe('Last run just now on the interval · 2 repositories');
|
||||
|
||||
// Only the control the user is in is spared: once they leave it, an update shows the stored value again.
|
||||
num.blur();
|
||||
app._onSessionUpdated({ id: SID, status: 'idle', gitFetchEnabled: true, gitFetchIntervalSeconds: 300 });
|
||||
expect(num.value).toBe('300');
|
||||
});
|
||||
|
||||
it('writes the clamped interval back when Enter saves with the field still focused', async () => {
|
||||
const app = openGitTab();
|
||||
app._apiJson = vi.fn(async (_url: string, opts: { body: unknown }) => ({ gitFetchSettings: opts.body }));
|
||||
app._onSessionUpdated({ id: SID, status: 'idle', gitFetchEnabled: true, gitFetchIntervalSeconds: 300 });
|
||||
const num = el('modalGitFetchInterval');
|
||||
num.focus();
|
||||
num.value = '12';
|
||||
|
||||
await app.autoSaveGitFetch();
|
||||
expect(app._apiJson).toHaveBeenCalledWith(`/api/sessions/${SID}/git-fetch-settings`, {
|
||||
method: 'POST',
|
||||
body: { enabled: true, intervalSeconds: 30 },
|
||||
});
|
||||
expect(dom.window.document.activeElement).toBe(num);
|
||||
expect(num.value).toBe('30');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Session Options → Git, with half an override', () => {
|
||||
it("shows the app's switch beside an interval-only override, because the scheduler runs it with that switch", () => {
|
||||
const app = openGitTab();
|
||||
app._onSessionUpdated({ id: SID, status: 'idle', gitFetchIntervalSeconds: 120 });
|
||||
expect(el('modalGitFetchFollow').checked).toBe(false);
|
||||
expect(el('modalGitFetchEnabled').checked).toBe(true);
|
||||
expect(el('modalGitFetchInterval').value).toBe('120');
|
||||
// Not following, so both rows are live, and touching either saves what they show.
|
||||
expect(el('modalGitFetchEnabled').disabled).toBe(false);
|
||||
expect(el('modalGitFetchInterval').disabled).toBe(false);
|
||||
});
|
||||
|
||||
it("shows the app's interval beside a switch-only override, because the scheduler runs it at that interval", () => {
|
||||
const app = openGitTab();
|
||||
app._onSessionUpdated({ id: SID, status: 'idle', gitFetchEnabled: true });
|
||||
expect(el('modalGitFetchFollow').checked).toBe(false);
|
||||
expect(el('modalGitFetchEnabled').checked).toBe(true);
|
||||
expect(el('modalGitFetchInterval').value).toBe('900');
|
||||
});
|
||||
|
||||
it('follows the app on both rows, inert, when the session holds no choice of its own', () => {
|
||||
const app = openGitTab();
|
||||
app._onSessionUpdated({ id: SID, status: 'idle' });
|
||||
expect(el('modalGitFetchFollow').checked).toBe(true);
|
||||
expect(el('modalGitFetchEnabled').checked).toBe(true);
|
||||
expect(el('modalGitFetchInterval').value).toBe('900');
|
||||
expect(el('modalGitFetchEnabled').disabled).toBe(true);
|
||||
expect(el('modalGitFetchInterval').disabled).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -246,6 +246,13 @@ describe('fetchEnvFor', () => {
|
||||
const env = fetchEnvFor({ ...BASE, GIT_SSH_COMMAND: 'ssh -i /home/t/personal' }, 'ssh -i /repo/key');
|
||||
expect(env.GIT_SSH_COMMAND).toBe('ssh -i /home/t/personal');
|
||||
});
|
||||
|
||||
it("leaves a GIT_SSH in the server's environment to git, which reads it last and would never see it under a written default", () => {
|
||||
const env = fetchEnvFor({ ...BASE, GIT_SSH: '/home/t/bin/work-ssh' }, null);
|
||||
expect(env.GIT_SSH_COMMAND).toBeUndefined();
|
||||
expect(env.GIT_SSH).toBe('/home/t/bin/work-ssh');
|
||||
expect(env.GIT_TERMINAL_PROMPT).toBe('0');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Real git, real local repository ─────────────────────────────────────────
|
||||
@@ -558,6 +565,42 @@ describe.skipIf(!gitPresent)('runFetch (the whole tree, not just the git parent)
|
||||
});
|
||||
});
|
||||
|
||||
// ─── One bound for the config read and the fetch ─────────────────────────────
|
||||
|
||||
describe.skipIf(process.platform === 'win32')('runFetch (one bound for the config read and the fetch)', () => {
|
||||
it('answers at the timeout when git never answers, not at twice it, because the core.sshCommand read spends part of the bound', async () => {
|
||||
// A `git` that never answers anything, first on PATH, so the read ahead of the fetch hangs exactly as long as
|
||||
// the fetch would. Both spawns take PATH from process.env at call time. It records its arguments, so the test
|
||||
// can tell which of the two it was asked to run.
|
||||
const bin = join(dir, 'bin');
|
||||
const calls = join(dir, 'calls');
|
||||
mkdirSync(bin);
|
||||
writeFileSync(join(bin, 'git'), `#!/bin/sh\necho "$*" >> '${calls}'\nexec sleep 30\n`, { mode: 0o755 });
|
||||
const savedPath = process.env.PATH;
|
||||
process.env.PATH = `${bin}:${savedPath ?? ''}`;
|
||||
try {
|
||||
const started = Date.now();
|
||||
const err = (await runFetch(dir, buildFetchArgs(), { timeoutMs: 1_000 }).catch((e) => e)) as {
|
||||
code?: unknown;
|
||||
killed?: boolean;
|
||||
};
|
||||
const elapsed = Date.now() - started;
|
||||
|
||||
expect(err.code).toBe('ETIMEDOUT');
|
||||
expect(err.killed).toBe(true);
|
||||
expect(describeFetchFailure(err).code).toBe('TIMEOUT');
|
||||
// One bound, not one per spawn: the read used all of it, so the fetch got nothing and was not started
|
||||
// (2019 ms here before the fix, when the fetch was armed with a fresh timeout of its own).
|
||||
expect(elapsed).toBeGreaterThanOrEqual(950);
|
||||
expect(elapsed).toBeLessThan(1_600);
|
||||
expect(readFileSync(calls, 'utf8').trim().split('\n')).toEqual(['config --get core.sshCommand']);
|
||||
} finally {
|
||||
if (savedPath === undefined) delete process.env.PATH;
|
||||
else process.env.PATH = savedPath;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ─── One run per folder, and one bound for the whole tick ────────────────────
|
||||
|
||||
describe.skipIf(!gitPresent)('fetchWorkspaceOnce (the join)', () => {
|
||||
|
||||
Reference in new issue
Block a user