The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): broadcast projects.changed when projects.db moves
Brooklyn Nicholson42d70d29ace2
diff --git a/apps/desktop/src/app/contrib/hooks/use-background-sync.test.ts b/apps/desktop/src/app/contrib/hooks/use-background-sync.test.tsindex c1ea8bf7b26..47241b88a3d 100644--- a/apps/desktop/src/app/contrib/hooks/use-background-sync.test.ts+++ b/apps/desktop/src/app/contrib/hooks/use-background-sync.test.ts@@ -665,7 +665,10 @@ describe('active transcript refresh', () => {await waitFor(() => expect(refreshProjectTree).toHaveBeenCalledTimes(1))})- it('refreshes the project list + tree on a projects.changed tick — CLI-created projects surface without a manual refresh (#56757)', async () => {+ it('refreshes the projects list and tree on a projects.changed tick (#53046, #56757)', async () => {+ // projects.db is written by the CLI and other windows — processes that never+ // touch the gateway's transports. Without the tick-driven refresh their+ // creates/folder edits never reach the Projects UI until a manual refresh.$changeEventsAvailable.set(true)renderSync(vi.fn(async () => undefined))@@ -673,7 +676,20 @@ describe('active transcript refresh', () => {act(() => notifyProjectsChanged())await waitFor(() => expect(refreshProjects).toHaveBeenCalledTimes(1))- await waitFor(() => expect(refreshProjectTree).toHaveBeenCalledTimes(1))+ await waitFor(() => expect(refreshProjectTree).toHaveBeenCalled())+ })++ it('does not refresh projects on a bare sessions.changed tick', async () => {+ // The two stores are independent: a sessions.changed refresh pulls the tree+ // (grouping of the same rows) but must not also fire a projects.list read.+ $changeEventsAvailable.set(true)++ renderSync(vi.fn(async () => undefined))++ act(() => notifySessionsChanged())++ await waitFor(() => expect(refreshProjectTree).toHaveBeenCalled())+ expect(refreshProjects).not.toHaveBeenCalled()})})diff --git a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts b/apps/desktop/src/app/contrib/hooks/use-background-sync.tsindex 4ffb678471c..5b9c99ea627 100644--- a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts+++ b/apps/desktop/src/app/contrib/hooks/use-background-sync.ts@@ -863,7 +863,6 @@ export function useBackgroundSync({}: BackgroundSyncParams): void {const changeEventsAvailable = useStore($changeEventsAvailable)const cronChangeTick = useStore($cronChangeTick)- const projectsChangeTick = useStore($projectsChangeTick)const activeTranscriptRefreshPendingRef = useRef<string | null>(null)const activeTranscriptReadRef = useRef<{ sessionKey: string; preservePending: boolean } | null>(null)// Tile reconcile state (#93942 slice 1): shared sequence guard + per-tile@@ -1225,19 +1224,29 @@ export function useBackgroundSync({)}, [changeEventsAvailable, cronChangeTick, gatewayState, refreshCronJobs])- // Projects created or switched by CLI / agent tooling write projects.db without any- // state.db movement, so sessions.changed never fires and the Projects sidebar used to- // go stale until a manual refresh (#56757). The gateway's change watcher now- // broadcasts projects.changed when projects.db moves; this effect refetches the- // project list + tree on that tick.+ // projects.changed (projects.db moved: a CLI `hermes projects create`, another+ // window's folder picker, a `set_primary` from the workspace settings) refreshes+ // both the projects list and the sidebar tree — the desktop's own mutations+ // refresh optimistically, so this only needs to cover writers in OTHER+ // processes, exactly the sessions.changed contract (#53046, #56757). The+ // refreshes keep the cached atoms on failure, so an older backend that never+ // broadcasts costs nothing. Subscribed (not mount-read) so a tick that landed+ // before this hook mounted — a stale value from a previous connection —+ // doesn't fire a refresh into a wiped store.useEffect(() => {- if (gatewayState !== 'open' || !changeEventsAvailable || projectsChangeTick === 0) {+ if (gatewayState !== 'open') {return}- void refreshProjects()- void refreshProjectTree()- }, [changeEventsAvailable, gatewayState, projectsChangeTick, refreshProjects, refreshProjectTree])+ return $projectsChangeTick.listen(tick => {+ if (tick <= 0) {+ return+ }++ void refreshProjects()+ void refreshProjectTree()+ })+ }, [gatewayState])// Preserve the pre-existing messaging behavior: refresh once when a// messaging transcript opens, then keep its visibility backstop. Desktopdiff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex b0e57422ad0..b4f8b8911c0 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -5527,7 +5527,7 @@ export interface BackendGatewayEventMap {'preview.restart.complete': SideAgentCompletePayload/** Progress line from the preview-restart agent. */'preview.restart.progress': PreviewRestartProgressPayload- /** projects.db moved; refetch the Projects sidebar. */+ /** projects.db moved; refetch the project list + tree. */'projects.changed': ChangeSignalPayload/** Affection reaction detected in the user's message (hearts etc.). */reaction: ReactionPayloaddiff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 67bf56e31c5..ecfe462b671 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -38256,7 +38256,7 @@},{"name": "projects.changed",- "summary": "projects.db moved; refetch the Projects sidebar.",+ "summary": "projects.db moved; refetch the project list + tree.","params": [{"name": "payload",diff --git a/tests/tui_gateway/test_change_watcher.py b/tests/tui_gateway/test_change_watcher.pyindex b1f2b3c6b2c..7641f073ed4 100644--- a/tests/tui_gateway/test_change_watcher.py+++ b/tests/tui_gateway/test_change_watcher.py@@ -65,6 +65,49 @@ def test_state_db_move_broadcasts_sessions_changed(watcher_home):assert ("sessions.changed", {}) in events+def test_projects_db_move_broadcasts_projects_changed(watcher_home):+ """#53046 / #56757: the CLI and other windows write projects.db directly, in+ processes that never touch this gateway's transports. Without a watch, a+ `hermes projects create` (or a set_primary / folder edit from another+ window) leaves the Desktop's project tree stale until an unrelated refresh."""+ home, events = watcher_home+ server._broadcast_watched_changes(now=0.0)++ (home / "projects.db").write_text("x")+ server._broadcast_watched_changes(now=10.0)++ assert ("projects.changed", {}) in events+++def test_served_profile_projects_db_move_broadcasts_projects_changed(watcher_home, monkeypatch):+ """A backend serving a sibling profile watches that profile's projects.db too —+ the sibling-home half of the sessions.changed contract (#53046)."""+ home, events = watcher_home+ coder_home = home / "profiles" / "coder"+ coder_home.mkdir(parents=True)+ monkeypatch.setattr(server, "_served_profile_homes", set())+ monkeypatch.setattr("hermes_cli.profiles.get_profile_dir", lambda name: home / "profiles" / name)+ assert server._profile_home("coder") == coder_home+ server._broadcast_watched_changes(now=0.0)++ (coder_home / "projects.db").write_text("x")+ server._broadcast_watched_changes(now=10.0)++ assert ("projects.changed", {}) in events+++def test_projects_sig_does_not_track_state_db_writes(watcher_home):+ """A state.db move must not fire projects.changed — the two stores are+ independent and their consumers refetch different surfaces."""+ home, events = watcher_home+ server._broadcast_watched_changes(now=0.0)++ (home / "state.db").write_text("x")+ server._broadcast_watched_changes(now=10.0)++ assert ("projects.changed", {}) not in events++def test_served_profile_store_move_broadcasts_sessions_changed(watcher_home, monkeypatch):"""A backend serving a sibling profile must see that profile's state.dbmove too — otherwise a routed profile's Bot Chat never refreshes (#99333)."""diff --git a/tui_gateway/change_watcher.py b/tui_gateway/change_watcher.pyindex 2632709430b..2531be7eee0 100644--- a/tui_gateway/change_watcher.py+++ b/tui_gateway/change_watcher.py@@ -131,6 +131,17 @@ def _sessions_sig():for name in ("state.db", "state.db-wal"))+def _projects_sig():+ """Newest mtime across projects.db (+ WAL) for the watcher home and every served+ sibling profile. The CLI and other windows write projects.db directly — nothing in+ their process touches this gateway's transports — so the file is the only shared+ signal, exactly like state.db (#53046, #56757)."""+ return _newest_mtime_ns(+ root / name+ for root in (_watcher_home(), *_served_profile_homes)+ for name in ("projects.db", "projects.db-wal"))++def _pairing_sig():"""Newest mtime across every profile's pairing ledgers (legacy ``pairing/`` and``platforms/pairing/``): the gateway process writes pending codes, so the files are the only@@ -203,8 +214,8 @@ _CHANGE_WATCHES: dict[str, tuple[float, Any, Any]] = {# Projects created/switched by CLI or agent tooling write projects.db without any# state.db movement, so sessions.changed never fires and the desktop Projects# sidebar goes stale until a manual refresh (#56757).- "projects.changed": (1.0, lambda: _home_mtime_ns("projects.db"), lambda: {}),"platforms.changed": (2.0, lambda: _home_mtime_ns("gateway_state.json"), lambda: {}),+ "projects.changed": (2.0, _projects_sig, lambda: {}),"pairing.changed": (2.0, _pairing_sig, lambda: {}),# 1s so a queued DM envelope reaches the Desktop's push-triggered drain fast."bot_relay.outbox.pending": (1.0, _bot_relay_outbox_sig, lambda: {})}diff --git a/tui_gateway/contracts/events.py b/tui_gateway/contracts/events.pyindex ead598759dc..092cf737ff0 100644--- a/tui_gateway/contracts/events.py+++ b/tui_gateway/contracts/events.py@@ -705,8 +705,8 @@ class ChangeSignalPayload(OpenPayload):event("cron.changed", ChangeSignalPayload, doc="cron/jobs.json moved; refetch the cron list.")event("sessions.changed", ChangeSignalPayload, doc="state.db moved; refetch the session list.")-event("projects.changed", ChangeSignalPayload, doc="projects.db moved; refetch the Projects sidebar.")event("platforms.changed", ChangeSignalPayload, doc="gateway_state.json moved; refetch platform status.")+event("projects.changed", ChangeSignalPayload, doc="projects.db moved; refetch the project list + tree.")event("pairing.changed", ChangeSignalPayload, doc="Pairing state moved; refetch pairing.")event("bot_relay.outbox.pending", ChangeSignalPayload, doc="A bot-relay outbox envelope is queued; drain it.")