The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): git-enrich lazily created session rows; never switch to a fallback lane label
Austin Pickett3da330fe23fe
diff --git a/apps/desktop/src/app/chat/sidebar/projects/workspace-group.tsx b/apps/desktop/src/app/chat/sidebar/projects/workspace-group.tsxindex 7d5d3bc11c2..32c79bbf7c9 100644--- a/apps/desktop/src/app/chat/sidebar/projects/workspace-group.tsx+++ b/apps/desktop/src/app/chat/sidebar/projects/workspace-group.tsx@@ -11,7 +11,7 @@ import { useStoreSelector } from '@/lib/use-session-slice'import { $sidebarShowAllSessions, setWorkspaceNodeOpen } from '@/store/layout'import { notifyError } from '@/store/notifications'import { newSessionInProfile, pinNewChatProfile, selectProfile } from '@/store/profile'-import { switchBranchInRepo } from '@/store/projects'+import { listRepoBranches, switchBranchInRepo } from '@/store/projects'import { $sessionProfilesUsage } from '@/store/session'import { $sidebarSessionRankIds } from '@/store/sidebar-sort'@@ -19,7 +19,7 @@ import { SidebarGroupRow, SidebarRowLead, SidebarRowLink, SidebarRowStack } fromimport { rankSessions } from '../order'import { PROJECT_PREVIEW_COUNT, SIDEBAR_GROUP_PAGE, useRevealedRows, useWorkspaceNodeOpen } from './model'-import type { SidebarSessionGroup } from './workspace-groups'+import { laneSwitchTarget, type SidebarSessionGroup } from './workspace-groups'import {WorkspaceAddButton,WorkspaceContextMenu,@@ -106,10 +106,15 @@ export function SidebarWorkspaceGroup({// currently sits on (`test0`, etc.), so explicitly switch first. A NON-GIT// lane (the backend heuristic's folder lane) has no branch to switch — `git// switch` there dies with "fatal: not a git repository" (#61362) — so the- // new session just lands in the folder as-is.+ // new session just lands in the folder as-is. Nor does a label git doesn't+ // know: the `main` fallback for rows with no recorded branch (#108694).if (group.isMain && group.isGit !== false && group.path && group.label) {try {- await switchBranchInRepo(group.path, group.label)+ const branch = laneSwitchTarget(group, await listRepoBranches(group.path))++ if (branch) {+ await switchBranchInRepo(group.path, branch)+ }} catch (err) {notifyError(err, t.statusStack.coding.switchFailed(group.label))diff --git a/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.test.ts b/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.test.tsindex 97088700090..6997c056a06 100644--- a/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.test.ts+++ b/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.test.ts@@ -8,6 +8,7 @@ import {baseName,excludeProjectSessions,kanbanWorktreeDir,+ laneSwitchTarget,liveSessionProjectId,mergeRepoWorktreeGroups,NO_PROJECT_ID,@@ -41,6 +42,30 @@ describe('baseName', () => {})})+describe('laneSwitchTarget (#108694)', () => {+ const main = { isMain: true, label: 'main', path: '/repo' }+ const local = (name: string) => ({ isRemote: false, name })++ it('skips the synthetic main fallback on a repo whose trunk is master', () => {+ expect(laneSwitchTarget(main, [local('master')])).toBeNull()+ })++ it('switches to a label git lists as a local branch', () => {+ expect(laneSwitchTarget(main, [local('master'), local('main')])).toBe('main')+ })++ it('switches to a remote-only branch git switch can DWIM', () => {+ expect(laneSwitchTarget(main, [local('dev'), { isRemote: true, name: 'origin/main' }])).toBe('main')+ })++ it('never switches non-git, linked, or unverifiable lanes', () => {+ expect(laneSwitchTarget({ ...main, isGit: false }, [local('main')])).toBeNull()+ expect(laneSwitchTarget({ ...main, isMain: false }, [local('main')])).toBeNull()+ expect(laneSwitchTarget({ ...main, path: null }, [local('main')])).toBeNull()+ expect(laneSwitchTarget(main, [])).toBeNull()+ })+})+describe('kanbanWorktreeDir', () => {it('matches a kanban task worktree (t_<hex>) and returns its .worktrees dir', () => {expect(kanbanWorktreeDir('/repo/.worktrees/t_aaaaaaaa')).toBe('/repo/.worktrees')diff --git a/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.ts b/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.tsindex 045eafe028d..716fda43010 100644--- a/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.ts+++ b/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.ts@@ -1,4 +1,4 @@-import type { HermesGitWorktree } from '@/global'+import type { HermesGitBranch, HermesGitWorktree } from '@/global'import type { ProjectInfo, SessionInfo } from '@/hermes'import { normalize } from '@/lib/text'@@ -133,6 +133,32 @@ export function kanbanWorktreeDir(path: string): null | string {/** Label for a main-checkout lane whose session recorded no branch. */export const DEFAULT_BRANCH_LABEL = 'main'+/**+ * The branch "+" on a lane should `git switch` to before opening a session, or+ * null to open on whatever the checkout is on now. A main-checkout lane label+ * is a display value: a row with no recorded `git_branch` falls back to+ * DEFAULT_BRANCH_LABEL (backend and live overlay alike). `git switch main` then+ * dies with "invalid reference: main" on a `master` repo (#108694). Only a+ * label that git lists as a branch (local, or a remote-tracking ref+ * `git switch` can DWIM) counts as a switch target.+ */+export function laneSwitchTarget(+ group: Pick<SidebarSessionGroup, 'isGit' | 'isMain' | 'label' | 'path'>,+ branches: readonly Pick<HermesGitBranch, 'isRemote' | 'name'>[]+): null | string {+ const label = group.label.trim()++ if (!group.isMain || group.isGit === false || !group.path || !label) {+ return null+ }++ const known = branches.some(branch =>+ branch.isRemote ? branch.name.slice(branch.name.indexOf('/') + 1) === label : branch.name === label+ )++ return known ? label : null+}+/** Id of the Home bucket (must match the backend tree's `NO_PROJECT_ID`). */export const NO_PROJECT_ID = '__no_project__'diff --git a/tests/tui_gateway/test_desktop_session_row_git_meta.py b/tests/tui_gateway/test_desktop_session_row_git_meta.pynew file mode 100644index 00000000000..a79f4203ae7--- /dev/null+++ b/tests/tui_gateway/test_desktop_session_row_git_meta.py@@ -0,0 +1,85 @@+"""A Desktop session's lazily created row must get git_branch/git_repo_root (#108784).++``session.create`` runs ``_hydrate_session_cwd`` before any row exists, so its cwd claim is a no-op; the row lands+later on the first submit via ``_ensure_session_db_row``. Without a probe there, desktop rows kept NULL git metadata+and their sidebar lane fell back to a fake ``main`` label (#108694).+"""++from __future__ import annotations++import subprocess++from hermes_state import SessionDB+from tui_gateway import server+++class _ImmediateThread:+ def __init__(self, *, target, **_kwargs):+ self._target = target++ def start(self):+ self._target()+++def _master_repo(path):+ subprocess.run(["git", "init", "-q", "-b", "master", str(path)], check=True)+ return path+++def _desktop_session(monkeypatch, tmp_path, cwd):+ db = SessionDB(db_path=tmp_path / "state.db")+ monkeypatch.setattr(server, "_get_db", lambda: db)+ monkeypatch.setattr(server, "_resolve_model", lambda: "test-model")+ monkeypatch.setattr(server, "_start_agent_build", lambda *a, **k: None)+ resp = server.handle_request({+ "id": "1", "method": "session.create", "params": {"cols": 80, "source": "desktop", "cwd": str(cwd)},+ })+ sid = resp["result"]["session_id"]+ # Patched only after create: session.create starts real Timers (Thread subclasses).+ monkeypatch.setattr(server.threading, "Thread", _ImmediateThread)+ return db, sid, server._sessions[sid], resp["result"]["stored_session_id"]+++def test_first_submit_row_records_git_branch_and_root(monkeypatch, tmp_path):+ repo = _master_repo(tmp_path / "repo")+ db, sid, session, key = _desktop_session(monkeypatch, tmp_path, repo)+ try:+ assert db.get_session(key) is None # lazy: no row until the first submit+ assert server._ensure_session_db_row(session) is True+ finally:+ server._sessions.pop(sid, None)++ row = db.get_session(key)+ assert row["cwd"] == str(repo)+ assert row["git_branch"] == "master"+ assert row["git_repo_root"]+++def test_row_git_probe_runs_once_per_session(monkeypatch, tmp_path):+ repo = _master_repo(tmp_path / "repo")+ db, sid, session, key = _desktop_session(monkeypatch, tmp_path, repo)+ probes = []+ real_branch = server.git_probe.branch+ monkeypatch.setattr(server.git_probe, "branch", lambda cwd: probes.append(cwd) or real_branch(cwd))+ try:+ for _ in range(3): # prompt.submit re-calls the upsert every turn+ assert server._ensure_session_db_row(session) is True+ finally:+ server._sessions.pop(sid, None)++ assert probes == [str(repo)]+ assert db.get_session(key)["git_branch"] == "master"+++def test_row_without_cwd_never_probes(monkeypatch, tmp_path):+ probes = []+ db, sid, session, key = _desktop_session(monkeypatch, tmp_path, tmp_path)+ monkeypatch.setattr(server.git_probe, "branch", lambda cwd: probes.append(cwd))+ session.update(cwd="", explicit_cwd=False)+ try:+ assert server._ensure_session_db_row(session) is True+ finally:+ server._sessions.pop(sid, None)++ assert not db.get_session(key)["cwd"]+ assert probes == []diff --git a/tui_gateway/session_workdir.py b/tui_gateway/session_workdir.pyindex a3fd1c20e42..6ccc251dab2 100644--- a/tui_gateway/session_workdir.py+++ b/tui_gateway/session_workdir.py@@ -459,6 +459,7 @@ def _ensure_session_db_row(session: dict) -> bool:session.pop("pending_archived", None)except Exception:logger.debug("failed to apply pending archived flag", exc_info=True)+ _schedule_row_git_meta(session, key, db)except Exception as exc:# Disk-full is not a soft failure: swallowed here, prompt.submit returns {"status":"streaming"} and the# message vanishes silently.@@ -466,6 +467,20 @@ def _ensure_session_db_row(session: dict) -> bool:return True+def _schedule_row_git_meta(session: dict, key: str, db) -> None:+ """Git-enrich a lazily created row once per live session. The row lands here with its cwd on the first submit, so+ ``_hydrate_session_cwd`` (which ran when no row existed) never claimed a probe, and a desktop row kept NULL+ git_branch/git_repo_root for life: its lane fell back to a fake ``main`` label (#108784). Probes the row's own+ cwd (the upsert never overwrites it), and only when enrichment is missing."""+ if session.get("row_git_meta_checked"):+ return+ session["row_git_meta_checked"] = True+ row = (db.get_session(key) if hasattr(db, "get_session") else None) or {}+ cwd = str(row.get("cwd") or "").strip()+ if cwd and not (row.get("git_branch") and row.get("git_repo_root")):+ _persist_session_cwd_and_schedule_git_meta(session, cwd, db=db)++def _workdir_reraise_disk_full(exc: BaseException, log_msg: str) -> None:"""Re-raise a disk-full write error (the caller must surface it); debug-log the rest."""from hermes_state_errors import is_disk_full_error