Skip to content

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.

feat(git): keep the desktop app on the newest main (#742)

Ruben Lütkeffd8fa37ba0f
diff --git a/dodaios/core/config.py b/dodaios/core/config.py
index 68330a0727..f6de8c903e 100644
--- a/dodaios/core/config.py
+++ b/dodaios/core/config.py
@@ -4538,6 +4538,17 @@ class AgenticIdeConfig(BaseModel):
),
)
+ follow_main: bool = Field(
+ default=False,
+ description=(
+ "Keep a desktop app that runs from a git checkout on the newest main: "
+ "fetch origin every minute, fast-forward, rebuild the frontend and restart "
+ "for new Python code once nothing would be lost (no mission, no live call). "
+ "Never merges, rebases, resets or stashes; local edits that would be "
+ "overwritten stop the update and are reported."
+ ),
+ )
+
pane_notifications: bool = Field(
default=True,
description=(
diff --git a/dodaios/core/config_writer.py b/dodaios/core/config_writer.py
index 28f98a3719..06f29ea750 100644
--- a/dodaios/core/config_writer.py
+++ b/dodaios/core/config_writer.py
@@ -118,6 +118,11 @@ def set_agentic_ide_prompt_writer(value: str, *, path: Path = DEFAULT_CONFIG_FIL
_patch_table(path, "agentic_ide", "prompt_writer", value)
+def set_agentic_ide_follow_main(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
+ """Set ``[agentic_ide] follow_main``: keep this checkout's app on the newest main."""
+ _patch_table(path, "agentic_ide", "follow_main", bool(enabled))
+
+
def set_brain_primary(name: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Set ``[brain] primary`` to the given provider name across all layers.
diff --git a/dodaios/core/main_follow.py b/dodaios/core/main_follow.py
new file mode 100644
index 0000000000..6fe0d3f4ca
--- /dev/null
+++ b/dodaios/core/main_follow.py
@@ -0,0 +1,357 @@
+"""Keep a desktop app that runs from a git checkout on the newest ``main``.
+
+Work lands on ``main`` through pull requests merged on GitHub; the desktop app
+runs the code in the checkout it was started from. Without a nudge that
+checkout stays on whatever commit it had, so merged work only shows once
+somebody pulls, rebuilds the frontend and restarts. :class:`MainFollower` is
+that nudge, for a person who opted in (``[agentic_ide] follow_main``):
+
+* Every minute or so it fetches ``origin/main``. When the checkout is on
+ ``main`` and ``origin`` is ahead, it fast-forwards. Never a merge, rebase,
+ reset or stash: a checkout with local commits, or with a local edit the
+ incoming commits would overwrite, is left alone and the reason reported.
+* The built frontend bundle (``dodaios/ui/web/dist``) is this follower's to
+ rebuild, so local copies of it never block the fast-forward.
+* A change under the frontend source rebuilds the bundle; open windows reload
+ themselves once the new bundle is on disk (``lib/bundleWatch.ts``).
+* A change to the Python code needs a restart. It happens when nothing would be
+ lost: no mission running, no live voice call, no speech session. Coding agent
+ panes live in their own terminal host and survive it. Until then the status
+ says a restart is pending.
+
+Only the instance that owns the ambient duties follows, and only a checkout
+whose top level is the folder this package was imported from: a linked
+worktree, a dev instance or an installed copy never pulls.
+"""
+
+from __future__ import annotations
+
+import os
+import shutil
+import subprocess
+import sys
+import threading
+import time
+from collections.abc import Callable
+from dataclasses import asdict, dataclass, field
+from pathlib import Path
+from typing import Any
+
+from loguru import logger
+
+from dodaios.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+#: Seconds between two looks at ``origin/main``.
+INTERVAL_S = 60.0
+#: The first look waits this long, so it never competes with the app's boot.
+FIRST_DELAY_S = 45.0
+_GIT_TIMEOUT_S = 120.0
+_BUILD_TIMEOUT_S = 20 * 60.0
+_INSTALL_TIMEOUT_S = 15 * 60.0
+
+#: The package folder this module lives in, as git names it ("jarvis" or a later name).
+PACKAGE = Path(__file__).resolve().parents[1].name
+DIST = f"{PACKAGE}/ui/web/dist"
+FRONTEND = f"{PACKAGE}/ui/web/frontend"
+#: Python outside these folders is never loaded by the running app.
+_NOT_APP_CODE = ("tests/", "scripts/", "docs/", "tools/")
+_NPM_INPUTS = {f"{FRONTEND}/package.json", f"{FRONTEND}/package-lock.json"}
+_PIP_INPUTS = {"pyproject.toml", "requirements.txt"}
+
+
+@dataclass(slots=True)
+class FollowStatus:
+ enabled: bool = False
+ #: The checkout can follow (a git checkout on ``main`` with an ``origin``).
+ eligible: bool = False
+ #: Why it does not follow, or what blocked the last update, in one sentence.
+ reason: str = ""
+ head: str = ""
+ remote: str = ""
+ last_check: float = 0.0
+ last_update: float = 0.0
+ #: The subject of the newest commit the last update brought in.
+ last_subject: str = ""
+ #: Updating, building or installing right now.
+ busy: str = ""
+ restart_pending: bool = False
+ #: Local edits that stop the fast-forward.
+ blocked_by: list[str] = field(default_factory=list)
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+
+def _run(
+ args: list[str], cwd: Path, *, timeout: float = _GIT_TIMEOUT_S
+) -> subprocess.CompletedProcess[str]:
+ env = dict(os.environ)
+ env["GIT_TERMINAL_PROMPT"] = "0"
+ env["GCM_INTERACTIVE"] = "never"
+ return subprocess.run(
+ args,
+ cwd=str(cwd),
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=timeout,
+ check=False,
+ env=env,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+
+
+def _git(
+ args: list[str], root: Path, *, timeout: float = _GIT_TIMEOUT_S
+) -> subprocess.CompletedProcess[str]:
+ return _run(["git", "-c", "core.quotePath=false", *args], root, timeout=timeout)
+
+
+def _last_line(result: subprocess.CompletedProcess[str]) -> str:
+ lines = [
+ line.strip() for line in (result.stderr or result.stdout or "").splitlines() if line.strip()
+ ]
+ return lines[-1] if lines else f"exit code {result.returncode}"
+
+
+def _overwritten(result: subprocess.CompletedProcess[str]) -> list[str]:
+ """The files git names when local edits would be overwritten by a merge."""
+ files: list[str] = []
+ collecting = False
+ for line in (result.stderr or "").splitlines():
+ if "would be overwritten" in line or "untracked working tree files" in line:
+ collecting = True
+ continue
+ if collecting:
+ if line.startswith(("\t", " ")) and line.strip():
+ files.append(line.strip())
+ elif line.strip():
+ collecting = False
+ return files
+
+
+def package_root() -> Path:
+ """The folder the running ``jarvis`` package was imported from (its parent)."""
+ return Path(__file__).resolve().parents[2]
+
+
+class MainFollower:
+ """Fetch, fast-forward, rebuild and restart, one round per :meth:`tick`."""
+
+ def __init__(
+ self,
+ root: Path,
+ *,
+ enabled: Callable[[], bool],
+ idle: Callable[[], bool],
+ restart: Callable[[], bool],
+ npm: str | None = None,
+ python: str | None = None,
+ ) -> None:
+ self.root = root
+ self._enabled = enabled
+ self._idle = idle
+ self._restart = restart
+ self._npm = npm
+ self._python = python or sys.executable
+ self.status = FollowStatus()
+ self._lock = threading.Lock()
+ self._stop = threading.Event()
+ self._wake = threading.Event()
+ self._thread: threading.Thread | None = None
+ self._logged_reason = ""
+
+ # ------------------------------------------------------------ lifecycle
+
+ def start(self, *, first_delay: float = FIRST_DELAY_S, interval: float = INTERVAL_S) -> None:
+ if self._thread is not None:
+ return
+
+ def loop() -> None:
+ if self._stop.wait(first_delay):
+ return
+ while not self._stop.is_set():
+ try:
+ self.tick()
+ except Exception as exc: # noqa: BLE001 -- a failed round must not end the follower
+ logger.opt(exception=exc).warning("Follow main: a round failed.")
+ self.status.busy = ""
+ self.status.reason = str(exc)
+ self._wake.wait(interval)
+ self._wake.clear()
+
+ self._thread = threading.Thread(target=loop, name="jarvis-follow-main", daemon=True)
+ self._thread.start()
+
+ def stop(self) -> None:
+ self._stop.set()
+ self._wake.set()
+
+ def poke(self) -> None:
+ """Look again now instead of at the next interval."""
+ self._wake.set()
+
+ # ------------------------------------------------------------ one round
+
+ def _note(self, reason: str) -> None:
+ self.status.reason = reason
+ if reason and reason != self._logged_reason:
+ logger.info("Follow main: {}", reason)
+ self._logged_reason = reason
+
+ def _eligible(self) -> bool:
+ top = _git(["rev-parse", "--show-toplevel"], self.root)
+ if top.returncode != 0:
+ self._note("This app does not run from a git checkout.")
+ return False
+ if Path(top.stdout.strip()).resolve() != self.root.resolve():
+ self._note("This app runs from a folder inside another checkout.")
+ return False
+ branch = _git(["symbolic-ref", "--quiet", "--short", "HEAD"], self.root).stdout.strip()
+ if branch != "main":
+ self._note(f"The checkout is on {branch or 'a detached commit'}, not main.")
+ return False
+ if _git(["remote", "get-url", "origin"], self.root).returncode != 0:
+ self._note("The checkout has no origin remote.")
+ return False
+ return True
+
+ def tick(self) -> FollowStatus:
+ """One round: maybe restart, fetch, fast-forward, rebuild. Returns the status."""
+ with self._lock:
+ status = self.status
+ status.enabled = bool(self._enabled())
+ if not status.enabled:
+ status.eligible = False
+ self._note("")
+ return status
+ status.eligible = self._eligible()
+ if not status.eligible:
+ return status
+ if status.restart_pending and self._idle():
+ self._try_restart()
+ return status
+ status.last_check = time.time()
+ fetched = _git(["fetch", "--quiet", "origin", "main"], self.root)
+ if fetched.returncode != 0:
+ self._note(f"Fetching main failed: {_last_line(fetched)}")
+ return status
+ status.head = _git(["rev-parse", "HEAD"], self.root).stdout.strip()
+ status.remote = _git(["rev-parse", "origin/main"], self.root).stdout.strip()
+ if not status.head or status.head == status.remote:
+ status.blocked_by = []
+ self._note("")
+ return status
+ if (
+ _git(["merge-base", "--is-ancestor", "HEAD", "origin/main"], self.root).returncode
+ != 0
+ ):
+ self._note("Local main has commits that origin/main does not; it is left as it is.")
+ return status
+ self._update(status)
+ if status.restart_pending and self._idle():
+ self._try_restart()
+ return status
+
+ def _update(self, status: FollowStatus) -> None:
+ listed = _git(["diff", "--name-only", "HEAD", "origin/main"], self.root)
+ changed = [line.strip() for line in listed.stdout.splitlines() if line.strip()]
+ status.busy = "update"
+ try:
+ if any(path.startswith(f"{DIST}/") for path in changed):
+ # The bundle is rebuilt below; a local copy of it must not block the update.
+ _git(["checkout", "--", DIST], self.root)
+ _git(["clean", "-fdq", "--", DIST], self.root)
+ merged = _git(["merge", "--ff-only", "--quiet", "origin/main"], self.root)
+ if merged.returncode != 0:
+ status.blocked_by = _overwritten(merged)
+ shown = ", ".join(status.blocked_by[:5]) or _last_line(merged)
+ self._note(f"Local changes block the update: {shown}")
+ return
+ status.blocked_by = []
+ status.last_update = time.time()
+ status.last_subject = _git(["log", "-1", "--format=%s"], self.root).stdout.strip()
+ status.head = _git(["rev-parse", "HEAD"], self.root).stdout.strip()
+ logger.info("Follow main: updated to {} ({})", status.head[:10], status.last_subject)
+ frontend = any(path.startswith((f"{FRONTEND}/", f"{DIST}/")) for path in changed)
+ backend = any(
+ (path.endswith(".py") and not path.startswith(_NOT_APP_CODE)) or path in _PIP_INPUTS
+ for path in changed
+ )
+ if any(path in _PIP_INPUTS for path in changed) and not self._install_python():
+ return
+ if frontend and not self._build(
+ npm_install=any(path in _NPM_INPUTS for path in changed)
+ ):
+ return
+ if backend:
+ status.restart_pending = True
+ self._note("")
+ finally:
+ status.busy = ""
+
+ def _build(self, *, npm_install: bool) -> bool:
+ npm = self._npm or shutil.which("npm")
+ if not npm:
+ self._note("npm is not installed, so the frontend could not be rebuilt.")
+ return False
+ folder = self.root / FRONTEND
+ if npm_install or not (folder / "node_modules").is_dir():
+ self.status.busy = "install"
+ installed = _run(
+ [npm, "ci", "--no-audit", "--no-fund"], folder, timeout=_INSTALL_TIMEOUT_S
+ )
+ if installed.returncode != 0:
+ self._note(f"Installing the frontend packages failed: {_last_line(installed)}")
+ return False
+ self.status.busy = "build"
+ built = _run([npm, "run", "build"], folder, timeout=_BUILD_TIMEOUT_S)
+ if built.returncode != 0:
+ self._note(f"Building the frontend failed: {_last_line(built)}")
+ return False
+ return True
+
+ def _install_python(self) -> bool:
+ self.status.busy = "install"
+ installed = _run(
+ [self._python, "-m", "pip", "install", "--quiet", "-r", "requirements.txt"],
+ self.root,
+ timeout=_INSTALL_TIMEOUT_S,
+ )
+ if installed.returncode != 0:
+ self._note(f"Installing the Python packages failed: {_last_line(installed)}")
+ return False
+ return True
+
+ def _try_restart(self) -> None:
+ if self._restart():
+ logger.info("Follow main: restarting to load the new code.")
+ self.status.restart_pending = False
+ else:
+ self._note("The new code needs a restart, and this app cannot restart itself.")
+
+
+# ------------------------------------------------------------------ the app's one follower
+
+_follower: MainFollower | None = None
+
+
+def get_follower() -> MainFollower | None:
+ return _follower
+
+
+def start_follower(
+ *, enabled: Callable[[], bool], idle: Callable[[], bool], restart: Callable[[], bool]
+) -> MainFollower | None:
+ """Start the app's follower once; only the instance that owns the ambient duties follows."""
+ global _follower
+ if _follower is not None:
+ return _follower
+ from dodaios.core.instance import current_instance
+
+ if not current_instance().owns_ambient_duties:
+ return None
+ _follower = MainFollower(package_root(), enabled=enabled, idle=idle, restart=restart)
+ _follower.start()
+ return _follower
diff --git a/dodaios/ui/web/agentic_ide_scm_routes.py b/dodaios/ui/web/agentic_ide_scm_routes.py
index a32961dd07..db1315b92a 100644
--- a/dodaios/ui/web/agentic_ide_scm_routes.py
+++ b/dodaios/ui/web/agentic_ide_scm_routes.py
@@ -491,6 +491,45 @@ def stash_drop(body: StashDropBody) -> dict:
return _ok()
+class FollowMainBody(BaseModel):
+ enabled: bool
+
+
+def _follow_status() -> dict:
+ from dodaios.core.main_follow import FollowStatus, get_follower
+
+ follower = get_follower()
+ if follower is None:
+ status = FollowStatus(reason="This app instance does not follow main.")
+ try:
+ from dodaios.core.config import load_config
+
+ status.enabled = bool(getattr(load_config().agentic_ide, "follow_main", False))
+ except Exception as exc: # noqa: BLE001 -- unreadable config: the toggle shows off
+ status.reason = f"The configuration could not be read: {exc}"
+ return status.to_dict()
+ return follower.status.to_dict()
+
+
[email protected]("/follow-main", summary="Does this app keep itself on the newest main?")
+def follow_main_status() -> dict:
+ return _follow_status()
+
+
[email protected]("/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."""
+ from dodaios.core import config_writer
+ from dodaios.core.main_follow import get_follower
+
+ config_writer.set_agentic_ide_follow_main(body.enabled)
+ follower = get_follower()
+ if follower is not None:
+ follower.status.enabled = body.enabled
+ follower.poke()
+ return _follow_status()
+
+
@router.get("/session-file", summary="Both sides of one file an agent session changed")
def session_file(
workspace_id: str = Query(..., min_length=1),
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.tsx
index 8f4f701e08..b4a47e956e 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
@@ -47,11 +47,14 @@ 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 posts: { path: string; body: Record<string, unknown> }[] = [];
const gets: string[] = [];
beforeEach(() => {
status = BASE;
+ follow = FOLLOW;
posts.length = 0;
gets.length = 0;
window.localStorage.clear();
@@ -61,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")) {
+ if (init?.method === "PUT") follow = { ...follow, ...JSON.parse(String(init.body)) };
+ return json(follow);
+ }
if (init?.method === "POST") {
posts.push({ path: url.replace(/^.*\/api\/agentic-ide\/git\//, ""), body: JSON.parse(String(init.body)) });
return json({ ok: true, commit: "abc1234", message: "feat: before", branch: "x", upstream: "origin/main", result: "merged" });
@@ -84,7 +91,7 @@ beforeEach(() => {
}
if (url.includes("/api/agentic-ide/panes")) {
const pane = (key: string, display_name: string, recap: string) => ({
- workspace_id: "w1", workspace_name: "App", folder: "/code/app", workspace_active: true, key, history_id: key, name: key,
+ workspace_id: "w1", workspace_name: "App", folder: "/code/app", workspace_active: true, key: key.toLowerCase(), history_id: key, name: key,
agent: display_name.toLowerCase(), display_name, accepts_prompts: true, status: "live", exit_code: null, activity: "idle",
activity_since: 0, worked: true, started_at: null, last_output_at: null, last_prompt: "", last_prompt_at: null, recap,
has_resume: true, readable: true, account: null, account_label: null, archived: false,
@@ -335,6 +342,17 @@ describe("GitOverviewTab — one agent session", () => {
});
});
+describe("GitOverviewTab — following main", () => {
+ it("turns following main on from the more menu and shows its state in the title", async () => {
+ render(<GitOverviewTab />);
+ fireEvent.click(await screen.findByTestId("scm-title-more"));
+ expect(screen.queryByTestId("scm-follow-status")).toBeNull();
+ fireEvent.click(await screen.findByTestId("scm-menu-follow-main"));
+ await vi.waitFor(() => expect(follow.enabled).toBe(true));
+ expect(await screen.findByTestId("scm-follow-status")).toBeTruthy();
+ });
+});
+
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.tsx
index e39477017c..181281fc03 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
@@ -15,7 +15,9 @@ import { useQuickInput } from "./scm/QuickInput";
import { ScmMenu, menuPointFor, type MenuItem } from "./scm/ScmMenu";
import { ScmViews } from "./scm/ScmViews";
import type { SessionPick } from "./scm/SessionChanges";
-import type { GraphScope } from "./scm/scmApi";
+import { scmApi, type FollowMain, type GraphScope } from "./scm/scmApi";
+import { agoLabel } from "./gitBadges";
+import { useRunLocale } from "@/components/runs/format";
import { scmStorage, useChoice, useScmCommands, useScmStatus, type CommitOptions } from "./scm/useScm";
export { resetGitOverviewCache } from "./RepositoryOverview";
@@ -62,13 +64,41 @@ export function GitOverviewTab() {
const [menu, setMenu] = useState<{ items: MenuItem[]; x: number; y: number } | null>(null);
const [goHead, setGoHead] = useState(0);
const [initializing, setInitializing] = useState(false);
+ const lang = useRunLocale();
+ // Does this app keep itself on the newest main? Read now and then while the tab is open.
+ const [follow, setFollow] = useState<FollowMain | null>(null);
+ useEffect(() => {
+ let alive = true;
+ let timer: number | undefined;
+ const read = () => {
+ scmApi
+ .followMain()
+ .then((answer) => alive && setFollow(answer))
+ .catch(() => alive && setFollow(null)) // an older backend has no such route: no toggle
+ .finally(() => {
+ if (alive) timer = window.setTimeout(read, 20_000 + Math.random() * 5_000);
+ });
+ };
+ read();
+ return () => {
+ alive = false;
+ window.clearTimeout(timer);
+ };
+ }, []);
+ const toggleFollow = useCallback(() => {
+ if (!follow) return;
+ scmApi
+ .setFollowMain(!follow.enabled)
+ .then(setFollow)
+ .catch((err: Error) => pushToast("error", err.message));
+ }, [follow, pushToast]);
// One agent session the Changes list is narrowed to (its pane's call-sign), per workspace.
const [sessionPane, setSessionPane] = useState<string | null>(null);
const panes = useWorkspacePanes(Boolean(workspaceId));
const workspacePanes = useMemo(() => panes.filter((row) => row.workspace_id === workspaceId), [panes, workspaceId]);
const session: SessionPick | null = useMemo(() => {
if (!sessionPane) return null;
- const row = workspacePanes.find((entry) => entry.key === sessionPane);
+ const row = workspacePanes.find((entry) => entry.name === sessionPane);
return { pane: sessionPane, agentName: row?.display_name || row?.agent || "", title: row?.recap || row?.last_prompt || "" };
}, [sessionPane, workspacePanes]);
useEffect(() => setSessionPane(null), [workspaceId]);
@@ -133,6 +163,9 @@ export function GitOverviewTab() {
const operation = status?.operation ?? "";
return [
viewSortMenu(settings, setSettings, t),
+ ...(follow
+ ? ([{ id: "follow-main", label: t("ide_side_panel.git.scm.follow_main"), checked: follow.enabled, run: toggleFollow }] 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() },
@@ -248,18 +281,18 @@ export function GitOverviewTab() {
],
},
];
- }, [status, settings, commands, runCommit, undoLastCommit, t]);
+ }, [status, settings, commands, runCommit, undoLastCommit, follow, toggleFollow, t]);
const pickSession = async () => {
type Pick = { pane: string | null };
const items = [
{ label: t("ide_side_panel.git.scm.all_changes"), icon: <Codicon name="git-compare" />, value: { pane: null } as Pick },
...workspacePanes.map((row) => ({
- label: row.display_name || row.agent ? `${row.key} · ${row.display_name || row.agent}` : row.key,
+ label: row.display_name || row.agent ? `${row.name} · ${row.display_name || row.agent}` : row.name,
description: row.recap || row.last_prompt || "",
- icon: <Codicon name={row.key === sessionPane ? "check" : "terminal"} />,
+ icon: <Codicon name={row.name === sessionPane ? "check" : "terminal"} />,
group: t("ide_side_panel.git.scm.sessions"),
- value: { pane: row.key } as Pick,
+ value: { pane: row.name } as Pick,
})),
];
const picked = await quick.pick(items, t("ide_side_panel.git.scm.pick_session"));
@@ -352,12 +385,33 @@ export function GitOverviewTab() {
}
const repository = status?.available;
+ const followTip = (state: FollowMain) =>
+ [
+ t("ide_side_panel.git.scm.follow_main_on"),
+ state.busy
+ ? t(`ide_side_panel.git.scm.follow_busy_${state.busy}`)
+ : state.restart_pending
+ ? t("ide_side_panel.git.scm.follow_restart_pending")
+ : state.reason,
+ state.last_update ? fill(t("ide_side_panel.git.scm.follow_updated"), { when: agoLabel(state.last_update, lang, t), subject: state.last_subject }) : "",
+ t("ide_side_panel.git.scm.follow_click_off"),
+ ]
+ .filter(Boolean)
+ .join("\n");
return (
<section data-testid="ide-git-tab" aria-label={t("ide_side_panel.git.aria")} className="scm-root relative flex h-full min-h-0 flex-col">
<div className="flex h-[35px] shrink-0 items-center pl-[20px] pr-[8px]">
<span className="min-w-0 flex-1 truncate text-[13px]" style={{ color: "var(--scm-title-fg)" }}>
{t("ide_side_panel.git.scm.title")}
</span>
+ {follow?.enabled && (
+ <IconButton label={followTip(follow)} testId="scm-follow-status" onClick={toggleFollow}>
+ <Codicon
+ name={follow.busy ? "sync" : follow.restart_pending ? "debug-restart" : follow.reason ? "warning" : "cloud-download"}
+ spin={Boolean(follow.busy)}
+ />
+ </IconButton>
+ )}
{repository && (
<IconButton label={t("ide_side_panel.git.scm.more_actions")} testId="scm-title-more" onClick={(event) => setMenu({ items: moreMenu(), ...menuPointFor(event.currentTarget) })}>
<Codicon name="ellipsis" />
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.ts
index 9688b94eeb..9c339a3f5d 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
@@ -101,6 +101,33 @@ export interface CommitFileDiff {
binary: boolean;
}
+/** Does this app keep itself on the newest main (`[agentic_ide] follow_main`)? */
+export interface FollowMain {
+ enabled: boolean;
+ eligible: boolean;
+ /** Why it does not follow, or what blocked the last update. */
+ reason: string;
+ head: string;
+ remote: string;
+ last_check: number;
+ last_update: number;
+ last_subject: string;
+ /** "update" | "install" | "build" | "" */
+ busy: string;
+ restart_pending: boolean;
+ blocked_by: string[];
+}
+
+async function put<T>(path: string, body: object): Promise<T> {
+ const res = await fetch(`${BASE}${path}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ });
+ if (!res.ok) throw await failure(res);
+ return (await res.json()) as T;
+}
+
export interface Stash {
ref: string;
message: string;
@@ -162,6 +189,8 @@ export const scmApi = {
get<CommitFileDiff>("/commit/file", { workspace_id, commit, path, original }),
sessionFile: (workspace_id: string, pane: string, path: string, base: string) =>
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 }),
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.json
index 735b3b9fb6..dc5876c747 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/de.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/de.json
@@ -8255,7 +8255,15 @@
"stage_session": "Offene Änderungen der Session bereitstellen",
"session_empty": "Diese Session hat noch keine Datei geändert, oder ihr Agent führt kein Protokoll seiner Änderungen.",
"session_committed": "committet",
- "session_generated": "{n} generierte Dateien ausgeblendet"
+ "session_generated": "{n} generierte Dateien ausgeblendet",
+ "follow_main": "App immer auf dem neuesten main halten",
+ "follow_main_on": "Diese App hält sich selbst auf dem neuesten main.",
+ "follow_busy_update": "Aktualisiere auf den neuesten main…",
+ "follow_busy_install": "Installiere Pakete für das Update…",
+ "follow_busy_build": "Baue die neue Oberfläche…",
+ "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."
}
},
"skills": {
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/en.json b/dodaios/ui/web/frontend/src/i18n/locales/en.json
index affad5e766..1efddeaefc 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/en.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/en.json
@@ -8255,7 +8255,15 @@
"stage_session": "Stage the Session's Pending Changes",
"session_empty": "This session has not changed any file yet, or its agent keeps no record of its edits.",
"session_committed": "committed",
- "session_generated": "{n} generated files hidden"
+ "session_generated": "{n} generated files hidden",
+ "follow_main": "Keep This App on the Latest Main",
+ "follow_main_on": "This app keeps itself on the latest main.",
+ "follow_busy_update": "Updating to the latest main…",
+ "follow_busy_install": "Installing packages for the update…",
+ "follow_busy_build": "Building the new interface…",
+ "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."
}
},
"skills": {
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/es.json b/dodaios/ui/web/frontend/src/i18n/locales/es.json
index 74106f7b78..5cfbdad115 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/es.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/es.json
@@ -8255,7 +8255,15 @@
"stage_session": "Preparar los cambios pendientes de la sesión",
"session_empty": "Esta sesión todavía no ha cambiado ningún archivo, o su agente no guarda registro de sus ediciones.",
"session_committed": "confirmado",
- "session_generated": "{n} archivos generados ocultos"
+ "session_generated": "{n} archivos generados ocultos",
+ "follow_main": "Mantener esta app en el main más reciente",
+ "follow_main_on": "Esta app se mantiene en el main más reciente.",
+ "follow_busy_update": "Actualizando al main más reciente…",
+ "follow_busy_install": "Instalando paquetes para la actualización…",
+ "follow_busy_build": "Construyendo la nueva interfaz…",
+ "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."
}
},
"skills": {
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/pt.json b/dodaios/ui/web/frontend/src/i18n/locales/pt.json
index b8cbf458f6..1f00be9ed7 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/pt.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/pt.json
@@ -8255,7 +8255,15 @@
"stage_session": "Preparar as alterações pendentes da sessão",
"session_empty": "Esta sessão ainda não alterou nenhum arquivo, ou o agente não guarda registro das edições.",
"session_committed": "com commit",
- "session_generated": "{n} arquivos gerados ocultos"
+ "session_generated": "{n} arquivos gerados ocultos",
+ "follow_main": "Manter esta app no main mais recente",
+ "follow_main_on": "Esta app se mantém no main mais recente.",
+ "follow_busy_update": "Atualizando para o main mais recente…",
+ "follow_busy_install": "Instalando pacotes para a atualização…",
+ "follow_busy_build": "Construindo a nova interface…",
+ "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."
}
},
"skills": {
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/zh.json b/dodaios/ui/web/frontend/src/i18n/locales/zh.json
index 7e6fabdab4..ff4f7b3894 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/zh.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/zh.json
@@ -8255,7 +8255,15 @@
"stage_session": "暂存该会话的待处理更改",
"session_empty": "此会话尚未更改任何文件,或其代理不记录编辑。",
"session_committed": "已提交",
- "session_generated": "已隐藏 {n} 个生成的文件"
+ "session_generated": "已隐藏 {n} 个生成的文件",
+ "follow_main": "让此应用始终保持在最新的 main",
+ "follow_main_on": "此应用会自动保持在最新的 main。",
+ "follow_busy_update": "正在更新到最新的 main…",
+ "follow_busy_install": "正在为更新安装软件包…",
+ "follow_busy_build": "正在构建新界面…",
+ "follow_restart_pending": "新代码已就绪;没有任务或通话进行时应用会自动重启。",
+ "follow_updated": "{when}已更新:{subject}",
+ "follow_click_off": "点击以停止跟随 main。"
}
},
"skills": {
diff --git a/dodaios/ui/web/server.py b/dodaios/ui/web/server.py
index 71f9c76d69..1f453e716e 100644
--- a/dodaios/ui/web/server.py
+++ b/dodaios/ui/web/server.py
@@ -104,6 +104,17 @@ def _is_backend_path(path: str) -> bool:
return path == "/api" or path.startswith(("/api/", "/ws"))
+def _follow_main_saved() -> bool:
+ """``[agentic_ide] follow_main`` as saved now (the in-memory config is read at boot)."""
+ try:
+ from dodaios.core.config import load_config
+
+ return bool(getattr(load_config().agentic_ide, "follow_main", False))
+ except Exception as exc: # noqa: BLE001 -- an unreadable file means "not opted in"
+ logger.debug("Follow main: the configuration could not be read: {}", exc)
+ return False
+
+
class _SpaFallbackRoute(APIRoute):
"""The SPA catch-all, invisible to API and socket paths.
@@ -484,8 +495,8 @@ class WebServer:
from .agent_mcp_routes import router as agent_mcp_router
from .agent_runtime_routes import router as agent_runtime_router
from .agentic_ide_git_routes import router as agentic_ide_git_router
- from .agentic_ide_scm_routes import router as agentic_ide_scm_router
from .agentic_ide_routes import router as agentic_ide_router
+ from .agentic_ide_scm_routes import router as agentic_ide_scm_router
from .antigravity_routes import router as antigravity_router
from .app_actions_routes import router as app_actions_router
from .appshot_routes import router as appshot_router
@@ -504,7 +515,6 @@ class WebServer:
from .commands_routes import router as commands_router
from .computer_use_routes import router as computer_use_router
from .computers_routes import router as computers_router
- from .server_pairing_routes import router as server_pairing_router
from .contacts_routes import router as contacts_router
from .control_routes import router as control_router
from .costs_routes import router as costs_router
@@ -556,6 +566,7 @@ class WebServer:
from .runtime_gateway_routes import router as runtime_gateway_router
from .screen_context_routes import router as screen_context_router
from .self_mod_routes import router as self_mod_router
+ from .server_pairing_routes import router as server_pairing_router
from .sessions_routes import router as sessions_router
from .settings_routes import router as settings_router
from .setup_report_routes import router as setup_report_router
@@ -2495,6 +2506,45 @@ class WebServer:
self._start_marketplace_refresh_scheduler
)
+ def _start_main_follower(self) -> None:
+ """Keep a git checkout's app on the newest main, when the person opted in.
+
+ The follower is a daemon thread whose first look waits well past boot;
+ here it is only created. ``[agentic_ide] follow_main`` is re-read every
+ round, so the toggle takes effect without a restart.
+ """
+ app = self.app
+
+ def enabled() -> bool:
+ return bool(getattr(self.cfg.agentic_ide, "follow_main", False)) or _follow_main_saved()
+
+ def idle() -> bool:
+ kontrollierer = getattr(app.state, "kontrollierer", None)
+ running = getattr(kontrollierer, "running_mission_ids", None)
+ if callable(running) and running():
+ return False
+ from dodaios.live.runtime import active
+
+ if any(getattr(session, "is_active", False) for session in active()):
+ return False
+ from dodaios.core.runtime_refs import get_speech_pipeline
+
+ pipeline = get_speech_pipeline()
+ in_session = getattr(pipeline, "is_session_active", None)
+ return not (callable(in_session) and in_session())
+
+ def restart() -> bool:
+ desktop = getattr(app.state, "desktop_app", None)
+ request = getattr(desktop, "request_restart", None)
+ return bool(request()) if callable(request) else False
+
+ try:
+ from dodaios.core.main_follow import start_follower
+
+ start_follower(enabled=enabled, idle=idle, restart=restart)
+ except Exception as exc: # noqa: BLE001 -- following main is a convenience, never a boot blocker
+ logger.opt(exception=exc).warning("Follow main did not start.")
+
def _start_local_models_health_monitor(self) -> None:
"""The Local models self-check task (best-effort, exactly once, off the boot path)."""
if self._local_models_health_monitor is not None:
@@ -3072,6 +3122,7 @@ class WebServer:
# hook covers normal desktop, headless, and direct WebServer starts.
self._schedule_marketplace_refresh_scheduler()
self._start_local_models_health_monitor()
+ self._start_main_follower()
self._schedule_local_models_autostart()
# Same reasoning, and the same three boot paths: a headless or
# browser-only install has no desktop shell to warm the realtime
diff --git a/tests/unit/core/test_main_follow.py b/tests/unit/core/test_main_follow.py
new file mode 100644
index 0000000000..151ef7dc8a
--- /dev/null
+++ b/tests/unit/core/test_main_follow.py
@@ -0,0 +1,202 @@
+"""Following main: fetch, fast-forward, rebuild, restart when idle — against a real git."""
+
+from __future__ import annotations
+
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from dodaios.core import main_follow
+from dodaios.core.main_follow import DIST, MainFollower
+
+pytestmark = pytest.mark.skipif(shutil.which("git") is None, reason="git is not installed")
+
+
[email protected](autouse=True)
+def _identity(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ monkeypatch.setenv("GIT_AUTHOR_NAME", "Test")
+ monkeypatch.setenv("GIT_AUTHOR_EMAIL", "[email protected]")
+ monkeypatch.setenv("GIT_COMMITTER_NAME", "Test")
+ monkeypatch.setenv("GIT_COMMITTER_EMAIL", "[email protected]")
+ monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1")
+ monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(tmp_path / "gitconfig"))
+
+
+def _git(cwd: Path, *args: str) -> str:
+ return subprocess.run(
+ ["git", *args], cwd=cwd, capture_output=True, text=True, check=True, encoding="utf-8"
+ ).stdout.strip()
+
+
+def _write(root: Path, rel: str, text: str) -> None:
+ target = root / rel
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(text.encode("utf-8"))
+
+
+def setup(tmp_path: Path) -> tuple[Path, Path]:
+ """(the app's checkout on main, a second clone that lands new work on origin)."""
+ remote = tmp_path / "remote.git"
+ _git(tmp_path, "init", "-q", "--bare", "-b", "main", str(remote))
+ app = tmp_path / "app"
+ _git(tmp_path, "clone", "-q", str(remote), str(app))
+ _write(app, "dodaios/core/a.py", "A = 1\n")
+ _write(app, f"{DIST}/index.html", "<html>v1</html>\n")
+ _write(app, "README.md", "readme\n")
+ _git(app, "add", ".")
+ _git(app, "commit", "-q", "-m", "first")
+ _git(app, "push", "-q", "-u", "origin", "main")
+ other = tmp_path / "other"
+ _git(tmp_path, "clone", "-q", str(remote), str(other))
+ return app, other
+
+
+def _land(other: Path, files: dict[str, str], subject: str) -> None:
+ for rel, text in files.items():
+ _write(other, rel, text)
+ _git(other, "add", ".")
+ _git(other, "commit", "-q", "-m", subject)
+ _git(other, "push", "-q")
+
+
+class Recorder:
+ def __init__(self, idle: bool = True) -> None:
+ self.idle = idle
+ self.restarts = 0
+ self.builds: list[bool] = []
+
+ def follower(self, root: Path, *, enabled: bool = True) -> MainFollower:
+ follower = MainFollower(
+ root, enabled=lambda: enabled, idle=lambda: self.idle, restart=self._restart
+ )
+
+ def build(*, npm_install: bool) -> bool:
+ self.builds.append(npm_install)
+ return True
+
+ follower._build = build # type: ignore[method-assign]
+ return follower
+
+ def _restart(self) -> bool:
+ self.restarts += 1
+ return True
+
+
+def test_does_nothing_unless_enabled(setup: tuple[Path, Path]) -> None:
+ app, other = setup
+ _land(other, {"dodaios/core/a.py": "A = 2\n"}, "feat: two")
+ status = Recorder().follower(app, enabled=False).tick()
+ assert not status.enabled and not status.eligible
+ assert (app / "dodaios/core/a.py").read_text(encoding="utf-8") == "A = 1\n"
+
+
+def test_a_branch_other_than_main_is_never_moved(setup: tuple[Path, Path]) -> None:
+ app, other = setup
+ _git(app, "switch", "-q", "-c", "feature")
+ _land(other, {"dodaios/core/a.py": "A = 2\n"}, "feat: two")
+ status = Recorder().follower(app).tick()
+ assert not status.eligible and "feature" in status.reason
+ assert _git(app, "rev-parse", "--abbrev-ref", "HEAD") == "feature"
+
+
+def test_fast_forwards_and_restarts_for_python_once_idle(setup: tuple[Path, Path]) -> None:
+ app, other = setup
+ _land(other, {"dodaios/core/a.py": "A = 2\n"}, "feat: two")
+ recorder = Recorder(idle=False)
+ follower = recorder.follower(app)
+ status = follower.tick()
+ assert (app / "dodaios/core/a.py").read_text(encoding="utf-8") == "A = 2\n"
+ assert status.last_subject == "feat: two" and status.restart_pending
+ assert recorder.restarts == 0 and recorder.builds == []
+ # Busy: the restart waits. Idle: the next round restarts.
+ follower.tick()
+ assert recorder.restarts == 0
+ recorder.idle = True
+ follower.tick()
+ assert recorder.restarts == 1 and not follower.status.restart_pending
+
+
+def test_a_frontend_change_rebuilds_and_a_local_bundle_never_blocks(
+ setup: tuple[Path, Path],
+) -> None:
+ app, other = setup
+ _write(app, f"{DIST}/index.html", "<html>local build</html>\n")
+ _write(app, f"{DIST}/assets/leftover.js", "old\n")
+ _land(
+ other,
+ {
+ "dodaios/ui/web/frontend/src/App.tsx": "export {};\n",
+ "dodaios/ui/web/frontend/package-lock.json": "{}\n",
+ f"{DIST}/index.html": "<html>v2</html>\n",
+ },
+ "feat(ui): new view",
+ )
+ recorder = Recorder()
+ status = recorder.follower(app).tick()
+ assert status.reason == "" and status.blocked_by == []
+ assert (app / f"{DIST}/index.html").read_text(encoding="utf-8") == "<html>v2</html>\n"
+ assert not (app / f"{DIST}/assets/leftover.js").exists()
+ assert recorder.builds == [True]
+ assert not status.restart_pending and recorder.restarts == 0
+
+
+def test_a_local_edit_the_update_would_overwrite_blocks_it(setup: tuple[Path, Path]) -> None:
+ app, other = setup
+ _write(app, "README.md", "my local notes\n")
+ _land(other, {"README.md": "new readme\n"}, "docs: readme")
+ head = _git(app, "rev-parse", "HEAD")
+ status = Recorder().follower(app).tick()
+ assert _git(app, "rev-parse", "HEAD") == head
+ assert status.blocked_by == ["README.md"] and "README.md" in status.reason
+ assert (app / "README.md").read_text(encoding="utf-8") == "my local notes\n"
+
+
+def test_an_unrelated_local_edit_rides_along(setup: tuple[Path, Path]) -> None:
+ app, other = setup
+ _write(app, "README.md", "my local notes\n")
+ _land(other, {"dodaios/core/b.py": "B = 1\n"}, "feat: b")
+ status = Recorder().follower(app).tick()
+ assert (app / "dodaios/core/b.py").exists() and status.blocked_by == []
+ assert (app / "README.md").read_text(encoding="utf-8") == "my local notes\n"
+
+
+def test_local_commits_on_main_are_left_alone(setup: tuple[Path, Path]) -> None:
+ app, other = setup
+ _write(app, "local.txt", "x\n")
+ _git(app, "add", ".")
+ _git(app, "commit", "-q", "-m", "local only")
+ _land(other, {"dodaios/core/a.py": "A = 2\n"}, "feat: two")
+ head = _git(app, "rev-parse", "HEAD")
+ status = Recorder().follower(app).tick()
+ assert _git(app, "rev-parse", "HEAD") == head
+ assert "Local main has commits" in status.reason
+
+
+def test_a_checkout_inside_another_is_not_followed(setup: tuple[Path, Path]) -> None:
+ app, _ = setup
+ status = Recorder().follower(app / "dodaios").tick()
+ assert not status.eligible
+
+
+def test_only_the_instance_with_ambient_duties_starts_one(monkeypatch: pytest.MonkeyPatch) -> None:
+ class Dev:
+ owns_ambient_duties = False
+
+ monkeypatch.setattr(main_follow, "_follower", None)
+ monkeypatch.setattr("dodaios.core.instance.current_instance", lambda: Dev())
+ started = main_follow.start_follower(
+ enabled=lambda: True, idle=lambda: True, restart=lambda: True
+ )
+ assert started is None and main_follow.get_follower() is None
+
+
+def test_python_outside_the_app_needs_no_restart(setup: tuple[Path, Path]) -> None:
+ app, other = setup
+ _land(other, {"tests/test_x.py": "def test_x():\n pass\n"}, "test: x")
+ recorder = Recorder()
+ status = recorder.follower(app).tick()
+ assert (app / "tests/test_x.py").exists()
+ assert not status.restart_pending and recorder.restarts == 0