Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(git): say when a git lock blocks following main, and remove a stale one on the person's click (#772)
Ruben Lütke604c19435ac0
diff --git a/dodaios/core/main_follow.py b/dodaios/core/main_follow.pyindex 6fe0d3f4ca..f48279d518 100644--- a/dodaios/core/main_follow.py+++ b/dodaios/core/main_follow.py@@ -57,6 +57,8 @@ FRONTEND = f"{PACKAGE}/ui/web/frontend"_NOT_APP_CODE = ("tests/", "scripts/", "docs/", "tools/")_NPM_INPUTS = {f"{FRONTEND}/package.json", f"{FRONTEND}/package-lock.json"}_PIP_INPUTS = {"pyproject.toml", "requirements.txt"}+#: A git lock this old belongs to no running command: one that was killed left it.+STALE_LOCK_S = 10 * 60.0@dataclass(slots=True)@@ -77,6 +79,10 @@ class FollowStatus:restart_pending: bool = False#: Local edits that stop the fast-forward.blocked_by: list[str] = field(default_factory=list)+ #: When a git lock that blocks the update was last written (epoch s); 0 = none.+ lock_since: float = 0.0+ #: That lock is older than :data:`STALE_LOCK_S`: offered for removal.+ lock_stale: bool = Falsedef to_dict(self) -> dict[str, Any]:return asdict(self)@@ -254,7 +260,55 @@ class MainFollower:self._try_restart()return status+ def _index_lock(self) -> Path | None:+ git_dir = _git(["rev-parse", "--absolute-git-dir"], self.root).stdout.strip()+ return Path(git_dir) / "index.lock" if git_dir else None++ def _locked(self, status: FollowStatus) -> bool:+ """Is the checkout's index locked? Says so, with its age, instead of failing later."""+ lock = self._index_lock()+ if lock is None or not lock.exists():+ status.lock_since = 0.0+ status.lock_stale = False+ return False+ try:+ since = lock.stat().st_mtime+ except OSError: # removed between the check and the read: not locked any more+ return False+ status.lock_since = since+ status.lock_stale = time.time() - since > STALE_LOCK_S+ self._note(+ "A git lock left by a stopped command blocks the update (.git/index.lock)."+ if status.lock_stale+ else "Another git command is working in this checkout; the update waits."+ )+ return True++ def clear_stale_lock(self) -> bool:+ """Remove the checkout's index lock, only while it is older than :data:`STALE_LOCK_S`.++ Called from the person's own click; a lock any younger may belong to a+ command still running and is never touched.+ """+ with self._lock:+ lock = self._index_lock()+ if lock is None or not lock.exists():+ self.status.lock_since = 0.0+ self.status.lock_stale = False+ return True+ if time.time() - lock.stat().st_mtime <= STALE_LOCK_S:+ return False+ lock.unlink()+ logger.info("Follow main: removed the stale git lock at the person's request.")+ self.status.lock_since = 0.0+ self.status.lock_stale = False+ self._note("")+ self.poke()+ return True+def _update(self, status: FollowStatus) -> None:+ if self._locked(status):+ returnlisted = _git(["diff", "--name-only", "HEAD", "origin/main"], self.root)changed = [line.strip() for line in listed.stdout.splitlines() if line.strip()]status.busy = "update"diff --git a/dodaios/ui/web/agentic_ide_scm_routes.py b/dodaios/ui/web/agentic_ide_scm_routes.pyindex db1315b92a..bdad25b409 100644--- a/dodaios/ui/web/agentic_ide_scm_routes.py+++ b/dodaios/ui/web/agentic_ide_scm_routes.py@@ -516,6 +516,21 @@ def follow_main_status() -> dict:return _follow_status()+ "/follow-main/clear-lock", summary="Remove a stale git lock that blocks following main"+)+def clear_follow_lock() -> dict:+ """Only a lock older than ten minutes is removed; a younger one answers 409."""+ from dodaios.core.main_follow import get_follower++ follower = get_follower()+ if follower is None:+ raise HTTPException(status_code=404, detail="This app instance does not follow main.")+ if not follower.clear_stale_lock():+ raise HTTPException(status_code=409, detail="The git lock is too recent to be stale.")+ return _follow_status()++@router.put("/follow-main", summary="Keep this app on the newest main, or stop")def set_follow_main(body: FollowMainBody) -> dict:"""Saved in ``[agentic_ide] follow_main``; the follower looks again at once."""diff --git a/dodaios/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.test.tsx b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.test.tsxindex 7168b188ae..d3a3bd639a 100644--- a/dodaios/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.test.tsx+++ b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.test.tsx@@ -1,7 +1,7 @@import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { GitOverviewTab, resetGitOverviewCache } from "./GitOverviewTab";-import type { GraphPage, ScmFile, ScmStatus } from "./scm/scmApi";+import type { FollowMain, GraphPage, ScmFile, ScmStatus } from "./scm/scmApi";import { useCodeEditorStore } from "@/store/codeEditor";import { useEventStore } from "@/store/events";import { useIdeChatStore } from "@/store/ideChat";@@ -47,8 +47,8 @@ const GRAPH: GraphPage = {};let status: ScmStatus = BASE;-const FOLLOW = { enabled: false, eligible: true, reason: "", head: "", remote: "", last_check: 0, last_update: 0, last_subject: "", busy: "", restart_pending: false, blocked_by: [] as string[] };-let follow = FOLLOW;+const FOLLOW: FollowMain = { enabled: false, eligible: true, reason: "", head: "", remote: "", last_check: 0, last_update: 0, last_subject: "", busy: "", restart_pending: false, blocked_by: [] as string[] };+let follow: FollowMain = FOLLOW;const posts: { path: string; body: Record<string, unknown> }[] = [];const gets: string[] = [];@@ -64,6 +64,10 @@ beforeEach(() => {vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {const url = String(input);const json = (body: unknown, code = 200) => new Response(JSON.stringify(body), { status: code, headers: { "Content-Type": "application/json" } });+ if (url.includes("/scm/follow-main/clear-lock")) {+ follow = { ...follow, lock_since: 0, lock_stale: false, reason: "" };+ return json(follow);+ }if (url.includes("/scm/follow-main")) {if (init?.method === "PUT") follow = { ...follow, ...JSON.parse(String(init.body)) };return json(follow);@@ -361,6 +365,19 @@ describe("GitOverviewTab — following main", () => {});});+describe("GitOverviewTab — a stale git lock", () => {+ it("offers to remove it only after a confirmation", async () => {+ follow = { ...FOLLOW, enabled: true, reason: "A git lock left by a stopped command blocks the update (.git/index.lock).", lock_since: 1_790_000_000, lock_stale: true };+ render(<GitOverviewTab />);+ await screen.findByTestId("scm-follow-status");+ fireEvent.click(await screen.findByTestId("scm-title-more"));+ fireEvent.click(await screen.findByTestId("scm-menu-follow-clear-lock"));+ expect(await screen.findByTestId("scm-choice")).toBeTruthy();+ fireEvent.click(screen.getByTestId("scm-choice-remove"));+ await vi.waitFor(() => expect(follow.lock_stale).toBe(false));+ });+});+describe("GitOverviewTab — graph", () => {it("draws the history with branch and tag badges and opens a commit's files", async () => {render(<GitOverviewTab />);diff --git a/dodaios/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.tsx b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.tsxindex 306f721dca..8dc141ef31 100644--- a/dodaios/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.tsx+++ b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.tsx@@ -85,6 +85,20 @@ export function GitOverviewTab() {window.clearTimeout(timer);};}, []);+ const clearFollowLock = useCallback(async () => {+ if (!follow?.lock_since) return;+ const since = new Date(follow.lock_since * 1000).toLocaleString(lang);+ const answer = await choice.ask({+ title: fill(t("ide_side_panel.git.scm.follow_clear_lock_title"), { since }),+ body: t("ide_side_panel.git.scm.follow_clear_lock_body"),+ buttons: [{ id: "remove", label: t("ide_side_panel.git.scm.follow_clear_lock"), destructive: true }],+ });+ if (answer !== "remove") return;+ scmApi+ .clearFollowLock()+ .then(setFollow)+ .catch((err: Error) => pushToast("error", err.message));+ }, [follow, lang, choice, pushToast, t]);const toggleFollow = useCallback(() => {if (!follow) return;scmApi@@ -167,6 +181,9 @@ export function GitOverviewTab() {...(follow? ([{ id: "follow-main", label: t("ide_side_panel.git.scm.follow_main"), checked: follow.enabled, run: toggleFollow }] as MenuItem[]): []),+ ...(follow?.enabled && follow.lock_stale+ ? ([{ id: "follow-clear-lock", label: `${t("ide_side_panel.git.scm.follow_clear_lock")}…`, run: () => void clearFollowLock() }] as MenuItem[])+ : []),{ kind: "separator", id: "m0" },{ id: "pull", label: t("ide_side_panel.git.scm.pull"), run: () => void commands.pull() },{ id: "push", label: t("ide_side_panel.git.scm.push"), run: () => void commands.push() },@@ -282,7 +299,7 @@ export function GitOverviewTab() {],},];- }, [status, settings, commands, runCommit, undoLastCommit, follow, toggleFollow, t]);+ }, [status, settings, commands, runCommit, undoLastCommit, follow, toggleFollow, clearFollowLock, t]);const pickSession = async () => {type Pick = { pane: string | null };diff --git a/dodaios/ui/web/frontend/src/components/agentic/sidePanel/git/scm/scmApi.ts b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/git/scm/scmApi.tsindex 9c339a3f5d..d8b71b2e63 100644--- a/dodaios/ui/web/frontend/src/components/agentic/sidePanel/git/scm/scmApi.ts+++ b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/git/scm/scmApi.ts@@ -116,6 +116,10 @@ export interface FollowMain {busy: string;restart_pending: boolean;blocked_by: string[];+ /** When a git lock blocking the update was last written (epoch s); 0 = none. */+ lock_since?: number;+ /** That lock is old enough to belong to no running command: it can be removed. */+ lock_stale?: boolean;}async function put<T>(path: string, body: object): Promise<T> {@@ -191,6 +195,7 @@ export const scmApi = {get<{ path: string; before: string | null; after: string | null; binary: boolean }>("/session-file", { workspace_id, pane, path, base }),followMain: () => get<FollowMain>("/follow-main", {}),setFollowMain: (enabled: boolean) => put<FollowMain>("/follow-main", { enabled }),+ clearFollowLock: () => post<FollowMain>("/follow-main/clear-lock", {}),stashes: (workspace_id: string) => get<{ stashes: Stash[] }>("/stashes", { workspace_id }),stage: (workspace_id: string, paths: string[]) => post("/stage", { workspace_id, paths }),diff --git a/dodaios/ui/web/frontend/src/i18n/locales/de.json b/dodaios/ui/web/frontend/src/i18n/locales/de.jsonindex cf690b330a..11891169ad 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/de.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/de.json@@ -8281,7 +8281,10 @@"follow_restart_pending": "Neuer Code ist da; die App startet neu, sobald keine Mission und kein Anruf läuft.","follow_updated": "Aktualisiert {when}: {subject}","follow_click_off": "Klicken, um main nicht mehr zu folgen.",- "session_diff_badge": "Änderungen von {pane}"+ "session_diff_badge": "Änderungen von {pane}",+ "follow_clear_lock": "Alten git-Lock entfernen",+ "follow_clear_lock_title": "Den git-Lock von {since} entfernen?",+ "follow_clear_lock_body": "Ein abgebrochener git-Befehl hat .git/index.lock zurückgelassen, und das hält diese App vom Aktualisieren ab. Nur entfernen, wenn in diesem Ordner gerade kein git-Befehl läuft."}},"skills": {diff --git a/dodaios/ui/web/frontend/src/i18n/locales/en.json b/dodaios/ui/web/frontend/src/i18n/locales/en.jsonindex 3563d6d7f9..3e6f9070ec 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/en.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/en.json@@ -8281,7 +8281,10 @@"follow_restart_pending": "New code is in; the app restarts as soon as no mission or call is running.","follow_updated": "Updated {when}: {subject}","follow_click_off": "Click to stop following main.",- "session_diff_badge": "Changes by {pane}"+ "session_diff_badge": "Changes by {pane}",+ "follow_clear_lock": "Remove the Stale Git Lock",+ "follow_clear_lock_title": "Remove the git lock left since {since}?",+ "follow_clear_lock_body": "A git command that was stopped mid-way left .git/index.lock behind, and it keeps this app from updating. Remove it only if no git command is running in this folder."}},"skills": {diff --git a/dodaios/ui/web/frontend/src/i18n/locales/es.json b/dodaios/ui/web/frontend/src/i18n/locales/es.jsonindex de9f28c16f..74035eb11c 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/es.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/es.json@@ -8281,7 +8281,10 @@"follow_restart_pending": "Hay código nuevo; la app se reinicia en cuanto no haya ninguna misión ni llamada en curso.","follow_updated": "Actualizado {when}: {subject}","follow_click_off": "Haz clic para dejar de seguir main.",- "session_diff_badge": "Cambios de {pane}"+ "session_diff_badge": "Cambios de {pane}",+ "follow_clear_lock": "Quitar el bloqueo de git antiguo",+ "follow_clear_lock_title": "¿Quitar el bloqueo de git que existe desde {since}?",+ "follow_clear_lock_body": "Un comando de git interrumpido dejó .git/index.lock, y eso impide que esta app se actualice. Quítalo solo si ningún comando de git se está ejecutando en esta carpeta."}},"skills": {diff --git a/dodaios/ui/web/frontend/src/i18n/locales/pt.json b/dodaios/ui/web/frontend/src/i18n/locales/pt.jsonindex 5637ecb4ec..78a769364b 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/pt.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/pt.json@@ -8281,7 +8281,10 @@"follow_restart_pending": "Há código novo; a app reinicia assim que nenhuma missão ou chamada estiver em andamento.","follow_updated": "Atualizado {when}: {subject}","follow_click_off": "Clique para deixar de seguir o main.",- "session_diff_badge": "Alterações de {pane}"+ "session_diff_badge": "Alterações de {pane}",+ "follow_clear_lock": "Remover o bloqueio antigo do git",+ "follow_clear_lock_title": "Remover o bloqueio do git que existe desde {since}?",+ "follow_clear_lock_body": "Um comando do git interrompido deixou .git/index.lock para trás, e isso impede que esta app se atualize. Remova só se nenhum comando do git estiver rodando nesta pasta."}},"skills": {diff --git a/dodaios/ui/web/frontend/src/i18n/locales/zh.json b/dodaios/ui/web/frontend/src/i18n/locales/zh.jsonindex dc56a72c46..3511a4a35a 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/zh.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/zh.json@@ -8281,7 +8281,10 @@"follow_restart_pending": "新代码已就绪;没有任务或通话进行时应用会自动重启。","follow_updated": "{when}已更新:{subject}","follow_click_off": "点击以停止跟随 main。",- "session_diff_badge": "{pane} 的更改"+ "session_diff_badge": "{pane} 的更改",+ "follow_clear_lock": "移除过期的 git 锁",+ "follow_clear_lock_title": "移除自 {since} 起存在的 git 锁?",+ "follow_clear_lock_body": "一个中途停止的 git 命令留下了 .git/index.lock,它会阻止此应用更新。仅在此文件夹中没有正在运行的 git 命令时移除。"}},"skills": {diff --git a/tests/unit/core/test_main_follow.py b/tests/unit/core/test_main_follow.pyindex 151ef7dc8a..5d2ba791c2 100644--- a/tests/unit/core/test_main_follow.py+++ b/tests/unit/core/test_main_follow.py@@ -200,3 +200,32 @@ def test_python_outside_the_app_needs_no_restart(setup: tuple[Path, Path]) -> Nostatus = recorder.follower(app).tick()assert (app / "tests/test_x.py").exists()assert not status.restart_pending and recorder.restarts == 0+++def test_a_git_lock_waits_and_only_an_old_one_is_offered_for_removal(+ setup: tuple[Path, Path],+) -> None:+ import os+ import time++ app, other = setup+ _land(other, {"jarvis_extra.txt": "x\n"}, "chore: extra")+ lock = app / ".git" / "index.lock"+ lock.write_bytes(b"")+ follower = Recorder().follower(app)++ status = follower.tick()+ assert status.lock_since and not status.lock_stale+ assert "Another git command" in status.reason+ assert not follower.clear_stale_lock() and lock.exists()++ old = time.time() - main_follow.STALE_LOCK_S - 60+ os.utime(lock, (old, old))+ status = follower.tick()+ assert status.lock_stale and "stopped command" in status.reason+ assert not (app / "jarvis_extra.txt").exists()++ assert follower.clear_stale_lock() and not lock.exists()+ status = follower.tick()+ assert (app / "jarvis_extra.txt").exists()+ assert status.lock_since == 0 and status.reason == ""