From bf9675fa849a76166c9dd965b37e9b827fbbc156 Mon Sep 17 00:00:00 2001 From: omartelo Date: Thu, 3 Dec 2026 15:18:24 -0300 Subject: [PATCH 1/3] feat(relay): tell an agent when a merged pull request conflicts with its work --- CHANGELOG.md | 1 + README.es.md | 1 + README.ja.md | 1 + README.ko.md | 1 + README.md | 1 + README.pt-BR.md | 1 + README.ru.md | 1 + README.zh-CN.md | 1 + docs/ceilings.md | 12 +++ docs/hooks/fixtures/notification.json | 1 + docs/hooks/notification.md | 6 +- docs/hooks/session-touched.md | 20 +++- internal/project/mergecollision.go | 118 +++++++++++++++++++++ internal/project/mergecollision_test.go | 131 ++++++++++++++++++++++++ internal/prompt/catalog.go | 3 + internal/prompt/en.go | 1 + internal/prompt/es.go | 1 + internal/prompt/ja.go | 1 + internal/prompt/ko.go | 1 + internal/prompt/pt_br.go | 1 + internal/prompt/ru.go | 1 + internal/prompt/zh_cn.go | 1 + internal/relay/editnote.go | 12 ++- internal/relay/envelope.go | 21 ++-- internal/relay/envelope_test.go | 2 + internal/relay/merged.go | 4 +- internal/relay/mergenote.go | 104 +++++++++++++++++++ internal/relay/mergenote_test.go | 117 +++++++++++++++++++++ internal/relay/relay.go | 6 ++ main.go | 1 + 30 files changed, 555 insertions(+), 18 deletions(-) create mode 100644 internal/project/mergecollision.go create mode 100644 internal/project/mergecollision_test.go create mode 100644 internal/relay/mergenote.go create mode 100644 internal/relay/mergenote_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index c73e9b86b..bd1974108 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Push and pull from the Git panel.** The branch item in the footer counts the commits to push and pull, and the panel's header offers the one the branch needs: Push, Pull, or Publish for a branch with no upstream yet. - **Install an agent from Settings, on this computer or on a server.** In Settings › Providers a provider that is not installed has an Install button that runs its official installer on the scope's machine; a project on a server with no agent installed offers the same from its empty screen. - **A chat waiting on the sessions it asked says which ones, and lets you stop it.** Over the message box, Waiting on names each session still owing an answer, one that needs you first with what it needs, a click opening it; Stop ends the turn. Only on Claude Code. +- **An agent is told when a merged pull request conflicts with what it is working on.** When the pull request of another session's checkout merges, the agents in the repository's other checkouts whose work conflicts with it get a note naming the files, at their next edit or command. An idle session is not woken for it; not in Cursor CLI's chat. ### Changed diff --git a/README.es.md b/README.es.md index f501a40a6..c69e9822a 100644 --- a/README.es.md +++ b/README.es.md @@ -168,6 +168,7 @@ distinto. | Una bifurcación cuelga de su sesión de origen en el árbol de la barra lateral | sí | sí | no | sí | no | no | no | no | | Aviso cuando retomas, desde la propia app del agente, una conversación que otra tarjeta tiene abierta | sí | en tu próximo prompt | en tu próximo prompt, sin probar | no | sí | en tu próximo prompt desde Crush 0.99.0; en versiones anteriores, en su próxima llamada a una herramienta | no | sí | | Avisado cuando edita un archivo que otra sesión editó minutos antes, y qué sesión fue | sí | sí | sí | sí | sí | desde Crush 0.99 | sí | con tu siguiente mensaje | +| Avisado, en su siguiente edición o comando, cuando un pull request fusionado desde el checkout de otra sesión entra en conflicto con su trabajo | sí | sí | sí | sí | sí | desde Crush 0.99 | en una terminal | con tu siguiente mensaje | | Abrir una sesión con un esfuerzo de razonamiento elegido | sí | sí | sí | no | sí | no | en el nombre del modelo | sí | | Abrir una sesión con ultracode activado | sí | no | no | no | no | no | no | no | | Varias cuentas lado a lado como perfiles, cada una con su propio inicio de sesión completo, y una sesión movida a otra cuenta que sigue en la misma tarjeta (Ajustes › Proveedores) | sí, con sus propios plugins, modelo y esfuerzo por defecto en cada perfil y el resto de los ajustes de Personal compartidos por todos | sí, con sus propios plugins, modelo y esfuerzo por defecto en cada perfil y el resto de los ajustes de Personal compartidos por todos | no | sí, con sesión iniciada desde una tarjeta de terminal; una sesión no puede pasar a otro perfil, porque sus conversaciones están en la base de datos que guarda el inicio de sesión; el último modelo elegido es el predeterminado de todos los perfiles | sí, con sesión iniciada desde una tarjeta de terminal, con sus propios modelos por defecto en cada perfil y el resto de sus ajustes compartidos por todos los perfiles | no medido | Linux y Windows (en macOS su inicio de sesión está en el Llavero), con sesión iniciada desde una tarjeta de terminal, con `mcp.json`, hooks y skills compartidos por todos los perfiles | solo Linux (macOS guarda su inicio de sesión en el Llavero y en Windows nada lo mueve), con sesión iniciada desde una tarjeta de terminal, con sus conversaciones y su modelo por defecto compartidos por todos los perfiles | diff --git a/README.ja.md b/README.ja.md index 3a7c4ee22..143700941 100644 --- a/README.ja.md +++ b/README.ja.md @@ -164,6 +164,7 @@ Gatekeeper や SmartScreen の警告が出ます。Homebrew でインストー | フォークはサイドバーのツリーで元のセッションの下に並ぶ | あり | あり | なし | あり | なし | なし | なし | なし | | 別のカードで開いている会話をエージェント本体のアプリで再開すると警告が出る | あり | 次のプロンプトで | 次のプロンプトで(未検証) | なし | あり | Crush 0.99.0 以降は次のプロンプトで(それより前は次のツール呼び出しで) | なし | あり | | 別のセッションが数分前に編集したファイルを編集すると、そのことと相手のセッションが伝えられる | あり | あり | あり | あり | あり | Crush 0.99 から | あり | 次のメッセージで | +| 別のセッションのチェックアウトからマージされたプルリクエストが自分の作業と競合すると、次の編集やコマンドのときに伝えられる | あり | あり | あり | あり | あり | Crush 0.99 から | ターミナルであり | 次のメッセージで | | 推論エフォートを指定してセッションを開く | あり | あり | あり | なし | あり | なし | モデル名で指定 | あり | | ultracode をオンにしてセッションを開く | あり | なし | なし | なし | なし | なし | なし | なし | | 複数のアカウントをプロファイルとして併用でき、それぞれが独立したログインを持つ。別のアカウントに移したセッションは同じカードのまま続く(設定 › プロバイダー) | あり。プラグインと既定のモデル、エフォートはプロファイルごとに持ち、それ以外の「個人」の設定はすべてのプロファイルで共有される | あり。プラグインと既定のモデル、エフォートはプロファイルごとに持ち、それ以外の「個人」の設定はすべてのプロファイルで共有される | なし | あり。ターミナルカードからログインする。会話がログインを保持するデータベースにあるため、セッションを別のプロファイルへ移すことはできない。最後に選んだモデルがすべてのプロファイルの既定になる | あり。ターミナルカードからログインし、既定のモデルはプロファイルごとに持ち、それ以外の設定はすべてのプロファイルで共有される | 未計測 | Linux と Windows(macOS ではログインがキーチェーンにある)。ターミナルカードからログインし、`mcp.json`、フック、スキルはすべてのプロファイルで共有される | Linux のみ(macOS ではログインがキーチェーンにあり、Windows ではそれを移す手段がない)。ターミナルカードからログインし、会話と既定のモデルはすべてのプロファイルで共有される | diff --git a/README.ko.md b/README.ko.md index 808c0c215..ac7f06da5 100644 --- a/README.ko.md +++ b/README.ko.md @@ -164,6 +164,7 @@ SmartScreen이 경고를 띄웁니다. Homebrew로 설치하면 Gatekeeper 경 | 포크는 사이드바 트리에서 원래 세션 아래에 놓임 | 예 | 예 | 아니요 | 예 | 아니요 | 아니요 | 아니요 | 아니요 | | 다른 카드에 열려 있는 대화를 에이전트 앱에서 직접 재개하면 경고 | 예 | 다음 프롬프트에서 | 다음 프롬프트에서, 미검증 | 아니요 | 예 | Crush 0.99.0부터 다음 프롬프트에서, 그 이전 버전은 다음 도구 호출 때 | 아니요 | 예 | | 다른 세션이 몇 분 전에 수정한 파일을 수정하면, 그 사실과 어느 세션인지 알려 줌 | 예 | 예 | 예 | 예 | 예 | Crush 0.99부터 | 예 | 다음 메시지를 보낼 때 | +| 다른 세션의 체크아웃에서 병합된 풀 리퀘스트가 자신의 작업과 충돌하면, 다음 수정이나 명령 때 알려 줌 | 예 | 예 | 예 | 예 | 예 | Crush 0.99부터 | 터미널에서 예 | 다음 메시지를 보낼 때 | | 원하는 reasoning effort로 세션 열기 | 예 | 예 | 예 | 아니요 | 예 | 아니요 | 모델 이름으로 지정 | 예 | | ultracode를 켠 채로 세션 열기 | 예 | 아니요 | 아니요 | 아니요 | 아니요 | 아니요 | 아니요 | 아니요 | | 여러 계정을 프로필로 나란히 두고 프로필마다 따로 로그인하며, 다른 계정으로 옮긴 세션이 같은 카드에서 이어짐(설정 › 프로바이더) | 예, 플러그인과 기본 모델, effort는 프로필마다 따로 두고 개인 프로필의 나머지 설정은 모든 프로필이 공유 | 예, 플러그인과 기본 모델, effort는 프로필마다 따로 두고 개인 프로필의 나머지 설정은 모든 프로필이 공유 | 아니요 | 예, 터미널 카드에서 로그인. 대화가 로그인 정보와 같은 데이터베이스에 있어서 세션을 다른 프로필로 옮길 수 없음. 마지막으로 고른 모델이 모든 프로필의 기본값이 됨 | 예, 터미널 카드에서 로그인하며 기본 모델은 프로필마다 따로 두고 나머지 설정은 모든 프로필이 공유 | 측정 안 됨 | Linux와 Windows(macOS에서는 로그인 정보가 키체인에 있음), 터미널 카드에서 로그인하며 `mcp.json`, hooks, skills는 모든 프로필이 공유 | Linux만(macOS는 로그인 정보를 키체인에 두고, Windows에서는 그 위치를 옮길 방법이 없음), 터미널 카드에서 로그인하며 대화와 기본 모델은 모든 프로필이 공유 | diff --git a/README.md b/README.md index 88d89ccbf..1211ac804 100644 --- a/README.md +++ b/README.md @@ -164,6 +164,7 @@ what lich can read back out of it, since each CLI records different things. | A fork hangs from its source session in the sidebar's tree | yes | yes | no | yes | no | no | no | no | | Warned when you resume, from the agent's own app, a conversation another card has open | yes | on your next prompt | on your next prompt, untested | no | yes | on your next prompt from Crush 0.99.0; before it, at its next tool call | no | yes | | Told when it edits a file another session edited minutes before, and which session it was | yes | yes | yes | yes | yes | from Crush 0.99 | yes | with your next message | +| Told, at its next edit or command, when a pull request merged from another session's checkout conflicts with its work | yes | yes | yes | yes | yes | from Crush 0.99 | in a terminal | with your next message | | Open a session at a chosen reasoning effort | yes | yes | yes | no | yes | no | in the model name | yes | | Open a session with ultracode on | yes | no | no | no | no | no | no | no | | Several accounts side by side as profiles, each with its own full login, and a session moved to another account carrying on in the same card (Settings › Providers) | yes, with its own plugins, default model and effort in each profile and Personal's other settings shared by all of them | yes, with its own plugins, default model and effort in each profile and Personal's other settings shared by all of them | no | yes, logged in from a terminal card; a session cannot move to another profile, since its conversations sit in the database that holds the login; the model picked last is every profile's default | yes, logged in from a terminal card, with its own default models in each profile and its other settings shared by every profile | not measured | Linux and Windows (on macOS its login is in the Keychain), logged in from a terminal card, with `mcp.json`, hooks and skills shared by every profile | Linux only (macOS keeps its login in the Keychain, and on Windows nothing moves it), logged in from a terminal card, with its conversations and default model shared by every profile | diff --git a/README.pt-BR.md b/README.pt-BR.md index 276ab5c56..f743a7332 100644 --- a/README.pt-BR.md +++ b/README.pt-BR.md @@ -166,6 +166,7 @@ o lich consegue ler de volta, porque cada CLI registra coisas diferentes. | Um fork fica pendurado na sessão de origem, na árvore da barra lateral | sim | sim | não | sim | não | não | não | não | | Aviso quando você retoma, pelo app do próprio agente, uma conversa que já está aberta em outro card | sim | no seu próximo prompt | no seu próximo prompt, sem teste | não | sim | no seu próximo prompt a partir do Crush 0.99.0; nas versões anteriores, na próxima chamada de tool | não | sim | | Avisado quando edita um arquivo que outra sessão editou minutos antes, e qual sessão foi | sim | sim | sim | sim | sim | a partir do Crush 0.99 | sim | com a sua próxima mensagem | +| Avisado, na próxima edição ou comando, quando um pull request mergeado a partir do checkout de outra sessão conflita com o trabalho dele | sim | sim | sim | sim | sim | a partir do Crush 0.99 | no terminal | com a sua próxima mensagem | | Abrir uma sessão com o esforço de raciocínio escolhido | sim | sim | sim | não | sim | não | no nome do modelo | sim | | Abrir uma sessão com ultracode ligado | sim | não | não | não | não | não | não | não | | Várias contas lado a lado como perfis, cada uma com login completo próprio, e uma sessão que muda de conta continua no mesmo card (Configurações › Provedores) | sim, com plugins, modelo e esforço padrão próprios em cada perfil e as demais configurações do Pessoal compartilhadas por todos | sim, com plugins, modelo e esforço padrão próprios em cada perfil e as demais configurações do Pessoal compartilhadas por todos | não | sim, com login feito num card de terminal; a sessão não muda de perfil, porque as conversas ficam no mesmo banco que guarda o login; o último modelo escolhido vira o padrão de todos os perfis | sim, com login feito num card de terminal, modelos padrão próprios em cada perfil e as demais configurações compartilhadas por todos os perfis | não medido | Linux e Windows (no macOS o login fica no Keychain), com login feito num card de terminal e `mcp.json`, hooks e skills compartilhados por todos os perfis | só Linux (o macOS guarda o login no Keychain, e no Windows nada consegue mudá-lo de lugar), com login feito num card de terminal e as conversas e o modelo padrão compartilhados por todos os perfis | diff --git a/README.ru.md b/README.ru.md index 741e022dd..ed9b5e05a 100644 --- a/README.ru.md +++ b/README.ru.md @@ -168,6 +168,7 @@ Linux, снятие флага карантина и переход со ста | Форк висит под исходной сессией в дереве боковой панели | да | да | нет | да | нет | нет | нет | нет | | Предупреждение, если вы возобновляете в приложении самого агента разговор, который открыт в другой карточке | да | при следующем промпте | при следующем промпте, не проверено | нет | да | при следующем промпте с Crush 0.99.0; в более ранних версиях при следующем вызове инструмента | нет | да | | Агенту сообщают, когда он правит файл, который несколько минут назад правила другая сессия, и какая именно | да | да | да | да | да | с Crush 0.99 | да | с вашим следующим сообщением | +| Агенту сообщают при следующей правке или команде, когда pull request, слитый из рабочей копии другой сессии, конфликтует с его работой | да | да | да | да | да | с Crush 0.99 | в терминале | с вашим следующим сообщением | | Открытие сессии с выбранным уровнем рассуждений | да | да | да | нет | да | нет | в названии модели | да | | Открытие сессии с включённым ultracode | да | нет | нет | нет | нет | нет | нет | нет | | Несколько аккаунтов рядом в виде профилей, у каждого свой полноценный логин, а сессия, переведённая на другой аккаунт, продолжает работу в той же карточке (Настройки › Провайдеры) | да, у каждого профиля свои плагины, модель и уровень рассуждений по умолчанию, а остальные настройки профиля «Личный» общие для всех | да, у каждого профиля свои плагины, модель и уровень рассуждений по умолчанию, а остальные настройки профиля «Личный» общие для всех | нет | да, логин из терминальной карточки; перевести сессию в другой профиль нельзя, потому что её разговоры лежат в той же базе данных, что и логин; последняя выбранная модель становится моделью по умолчанию для всех профилей | да, логин из терминальной карточки, у каждого профиля свои модели по умолчанию, остальные настройки общие для всех профилей | не измерялось | Linux и Windows (на macOS логин хранится в связке ключей), логин из терминальной карточки, `mcp.json`, хуки и навыки общие для всех профилей | только Linux (на macOS логин хранится в связке ключей, а на Windows его ничем не перенести), логин из терминальной карточки, разговоры и модель по умолчанию общие для всех профилей | diff --git a/README.zh-CN.md b/README.zh-CN.md index e2ff83f76..dd59808fa 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -160,6 +160,7 @@ tarball、清除隔离标记,以及从旧的 Homebrew formula 升级,见 [IN | 分叉出的会话在侧边栏的树中挂在源会话下 | 有 | 有 | 无 | 有 | 无 | 无 | 无 | 无 | | 在智能体自己的应用里恢复另一张卡片已打开的对话时会发出警告 | 有 | 在你下一次发提示词时 | 在你下一次发提示词时,未测试 | 无 | 有 | Crush 0.99.0 起在你下一次发提示词时;更早版本在它下一次调用工具时 | 无 | 有 | | 编辑了另一个会话几分钟前编辑过的文件时会被告知,并说明是哪个会话 | 有 | 有 | 有 | 有 | 有 | Crush 0.99 起 | 有 | 随你的下一条消息 | +| 从另一个会话的 checkout 合并的拉取请求与自己的工作有冲突时,会在下一次编辑或命令时被告知 | 有 | 有 | 有 | 有 | 有 | Crush 0.99 起 | 终端中有 | 随你的下一条消息 | | 以指定的推理强度打开会话 | 有 | 有 | 有 | 无 | 有 | 无 | 写在模型名里 | 有 | | 以 ultracode 模式打开会话 | 有 | 无 | 无 | 无 | 无 | 无 | 无 | 无 | | 多个账号以配置档案并存,各自独立完整登录;会话换到另一个账号后仍在同一张卡片里继续(设置 › 提供商) | 有,每个配置档案有自己的插件、默认模型和推理强度,“个人”的其他设置由所有配置档案共用 | 有,每个配置档案有自己的插件、默认模型和推理强度,“个人”的其他设置由所有配置档案共用 | 无 | 有,在终端卡片里登录;会话不能换到另一个配置档案,因为对话和登录信息存在同一个数据库里;最后选的模型是所有配置档案的默认模型 | 有,在终端卡片里登录,每个配置档案有自己的默认模型,其他设置由所有配置档案共用 | 未测量 | Linux 和 Windows(macOS 上登录信息在钥匙串里),在终端卡片里登录,`mcp.json`、hooks 和 skills 由所有配置档案共用 | 仅 Linux(macOS 把登录信息放在钥匙串里,Windows 上没有办法迁移),在终端卡片里登录,对话和默认模型由所有配置档案共用 | diff --git a/docs/ceilings.md b/docs/ceilings.md index 1384a7246..5c306a564 100644 --- a/docs/ceilings.md +++ b/docs/ceilings.md @@ -853,6 +853,18 @@ work when nobody knows it and that the call site never shows. The mechanism and not read either, but its `PreInvocation` runs before every model call, so there the note arrives before the next step. Crush older than v0.99.0 has no `PostToolUse` and gets no note. Edits made through a shell tool name no path and are never seen. +- **A merge conflict note is read once, at the session's next write, and only for a merge lich saw** + (`internal/relay/mergenote.go`, `internal/project/mergecollision.go`). `AnnounceMerge` leaves the merge to every + live agent in another checkout, and the session's next touched report has it read against its work, uncommitted + work included; the note is the answer to a later report, since the read fetches and the hook gives up after a + second. So an idle session costs nothing and hears nothing until it works again, one whose turn ends first hears + in its next turn, and a conflict it makes after that one read is not told. The merges are those of the merge + notice below (a pull request from no checkout lich follows is never seen), and a restart forgets the ones not yet + told. The base is read from `origin`: a fork whose pull requests merge on another remote gets no note, nor does a + fetch that fails or a git older than 2.38. Only a conflict counts, not a shared file: of 299 neighbouring merges + of this repository 75% shared a file and 30% conflicted, so the same work done in two different files is not + caught. It rides the hooks of the edit-overlap note and has its gaps: none on a Crush older than v0.99.0, with + the next prompt on Kiro CLI, and none in Cursor CLI's chat, which runs no hooks. ## Transcripts, cost and plan usage diff --git a/docs/hooks/fixtures/notification.json b/docs/hooks/fixtures/notification.json index 1ec16f088..3d5d58dc4 100644 --- a/docs/hooks/fixtures/notification.json +++ b/docs/hooks/fixtures/notification.json @@ -14,6 +14,7 @@ {"name": "notice: checks failed", "view": "chat", "envelope": "\nThe checks failed on pull request #1210 at commit 3f2a9c1.\n"}, {"name": "notice: scheduled prompt", "view": "terminal", "envelope": "\nScheduled for 09:00, delivered 4 minutes late.\nRebase on main and run the gate.\n"}, {"name": "notice: edit overlap", "view": "chat", "envelope": "\nThe lich session \"Docs sweep\", which shares this checkout, also edited /src/lich/internal/relay/conn.go 4 minutes ago and may still be working on it. Re-read what it changed before building on it, and coordinate with that session through send_to_session rather than undoing its change.\n"}, + {"name": "notice: merge conflict", "view": "chat", "envelope": "\nPull request #1210 \"fix(relay): handshake race\" was merged into main.\nThat merge conflicts with the work in this checkout in: internal/relay/conn.go, internal/relay/relay.go. Before going on, read what it changed there with `git diff HEAD...origin/main -- `: part of what you are doing may already be done. Do not merge or rebase in the middle of your task because of this notice alone.\n"}, {"name": "escaping: attributes escaped, element text verbatim", "view": "chat", "envelope": "\nanswered\nRun a && b, then check that stays text.\n"}, {"name": "two envelopes in one message, oldest first, one blank line apart", "view": "chat", "envelope": "\nanswered\nThe handshake raced on reconnect; fixed in internal/relay/conn.go, test added.\n\n\n\nexpired\n"}, {"name": "request: resolve conflicts", "view": "chat", "envelope": "\nResolve the conflicts\n\n\nPull request #1210 (fix-412-handshake) has merge conflicts with main in these files. Resolve them:\n\n- internal/relay/conn.go\n- internal/relay/relay.go\n"}, diff --git a/docs/hooks/notification.md b/docs/hooks/notification.md index 0bd40b33a..63141ab4d 100644 --- a/docs/hooks/notification.md +++ b/docs/hooks/notification.md @@ -46,7 +46,7 @@ of the contract. | `url` | `request` with topic `browser-notes` or `issue` | the page the notes were left on, or the issue | | `image` | `request` with topic `browser-notes` | the path of the sketch the person drew on the page, when there is one | | `issue`, `title` | `request` with topic `issue` | the issue's number and title | -| `topic` | `notice`, `request` | what the notice is: `checks-failed`, `checks-passed`, `review`, `scheduled`, `usage-reset`, `compacted`, `unanswered`, `loop`, `handoff`, `edit-overlap`; what the request is: `conflicts`, `checks`, `review-thread`, `review-comments`, `browser-notes`, `issue` | +| `topic` | `notice`, `request` | what the notice is: `checks-failed`, `checks-passed`, `review`, `scheduled`, `usage-reset`, `compacted`, `unanswered`, `loop`, `handoff`, `edit-overlap`, `merge-conflict`; what the request is: `conflicts`, `checks`, `review-thread`, `review-comments`, `browser-notes`, `issue` | ### Kinds @@ -89,7 +89,9 @@ pull request's checks or a new review, a scheduled prompt, a usage limit that reset, the errands a compaction may have summarised away, a turn that ended with requests unanswered, a loop warning between two sessions, a file another session wrote minutes before this one did (`edit-overlap`, the answer of a -[session-touched](session-touched.md) report rather than a typed note), and the +[session-touched](session-touched.md) report rather than a typed note), a merge +that conflicts with the session's work (`merge-conflict`, answered the same +way), and the note a session hands its successor (`handoff`: a notice and not a task, since nothing is owed back to a session done with the work). A scheduled prompt gets its envelope whether it is late or on time: its summary says when it was due, and how late diff --git a/docs/hooks/session-touched.md b/docs/hooks/session-touched.md index d4de61042..e0a4a79a1 100644 --- a/docs/hooks/session-touched.md +++ b/docs/hooks/session-touched.md @@ -54,8 +54,8 @@ poll this hook beats. Responses: - `204`: nothing to say (a held touch always). -- `200` with `{"note": ""}`: one or more edit-overlap - envelopes ([notification.md](notification.md)), to be handed to the model the +- `200` with `{"note": ""}`: one or more + merge-conflict and edit-overlap envelopes ([notification.md](notification.md)), to be handed to the model the way the provider takes a hook's extra context (Delivery, below). - `401` invalid token · `403` the token belongs to another session · `400` invalid body (an empty path, or a `collect` with `paths` or `hold`). @@ -90,6 +90,20 @@ share one. not hold. It is told once, and dropped unsaid when B's edit leaves the window first or B stops running. +## Merge conflict + +The same answer carries a second note: a pull request merged from another +checkout of the repository conflicts with the work in this session's. + +- A merge is left for every live session outside the merged checkout. The + session's next request, of any shape, starts the read, and a later one that + can carry a note is answered with it: the read fetches the base, which + outlasts a hook's timeout. A client does nothing new. +- It is one `notice` envelope per merge, `topic="merge-conflict"`, `pr` and + `branch` naming the merged one, its `` naming the base and the + conflicting files. Merge conflicts come before edit overlaps, one blank line + apart. Each is told once. + ## Event → action mapping | Provider | Hook | Paths from | Note delivered by | @@ -181,6 +195,8 @@ it gets the refresh and never a note. and calls `refreshPath` (`native/cmd/lich-native/gitstate.go`), which fetches that path now, ahead of the poll tick. A no-op when the session lives in a project not on screen, so it costs no git call. +- **Merge conflict**: `internal/relay/mergenote.go`, and + `internal/project/mergecollision.go` for the files. - **Edit overlap**: `internal/relay/editnote.go`, `Service.Touched`: who last wrote each path, the held overlaps, and the envelope. diff --git a/internal/project/mergecollision.go b/internal/project/mergecollision.go new file mode 100644 index 000000000..915d9b2f8 --- /dev/null +++ b/internal/project/mergecollision.go @@ -0,0 +1,118 @@ +package project + +import ( + "log/slog" + "os" + "path/filepath" + "slices" + "strings" +) + +// HeadCommit is the commit checked out at path, "" when git answers none. +func (s *Service) HeadCommit(path string) string { + out, _ := gitQuiet(path, "rev-parse", "--verify", "--quiet", "HEAD") + return strings.TrimSpace(out) +} + +// MergeCollisions is the files in which checkout's work, uncommitted work +// included, conflicts with base now that the branch at commit merged into it. +// Only files that branch changed count: a conflict with older work on base is +// not this merge's news. Nil when there is none, when checkout is another +// repository, or when it is already merging. +// +// It reaches the network, since the merge happened on the forge. The conflicts +// are read against base rather than against commit: a squashed branch stays a +// stranger to a checkout that already pulled it. +func (s *Service) MergeCollisions(checkout, commit, base string) []string { + if _, known := gitQuiet(checkout, "cat-file", "-e", commit+"^{commit}"); !known { + return nil + } + if mergingFrom(checkout) != "" { + return nil + } + if err := fetchBase(checkout, "origin", base); err != nil { + slog.Debug("project: fetch a merged base", "checkout", checkout, "base", base, "err", err) + } + ref := "refs/remotes/origin/" + base + theirs := branchFiles(checkout, commit, ref) + if len(theirs) == 0 { + return nil + } + conflicts, ok := mergeConflicts(checkout, ref, workSnapshot(checkout)) + if !ok { + return nil + } + files := append(conflicts, untrackedOn(checkout, ref)...) + files = slices.DeleteFunc(files, func(f string) bool { return !slices.Contains(theirs, f) }) + slices.Sort(files) + return slices.Compact(files) +} + +// branchFiles is the files the branch at commit changed since it left base. A +// merge that was not squashed put commit itself on base, so nothing is left to +// compare there, and the files are the ones changed since it left checkout. +func branchFiles(checkout, commit, base string) []string { + fork, ok := gitQuiet(checkout, "merge-base", commit, base) + if ok && strings.TrimSpace(fork) == commit { + fork, ok = gitQuiet(checkout, "merge-base", commit, "HEAD") + } + if !ok { + return nil + } + out, _ := gitQuiet(checkout, "diff", "--name-only", "--no-relative", "--no-renames", "-z", strings.TrimSpace(fork), commit) + return nulPaths(out) +} + +// untrackedOn is the files untracked in checkout that ref has: a merge would +// refuse to write over them, and merge-tree, which reads commits, misses them. +func untrackedOn(checkout, ref string) []string { + out, _ := gitQuiet(checkout, "ls-files", "--others", "--exclude-standard", "--full-name", "-z", "--", ":/") + untracked := nulPaths(out) + if len(untracked) == 0 { + return nil + } + out, _ = gitQuiet(checkout, "ls-tree", "-r", "--full-tree", "--name-only", "-z", ref) + onRef := map[string]bool{} + for _, path := range nulPaths(out) { + onRef[path] = true + } + return slices.DeleteFunc(untracked, func(f string) bool { return !onRef[f] }) +} + +// workSnapshot is a commit of checkout's tracked files as they are on disk, +// HEAD when nothing is uncommitted or git cannot write one. It is made from a +// copy of the index: stash create refreshes the index it reads under +// index.lock, which an agent's own commit at that moment would fail on. +func workSnapshot(checkout string) string { + const clean = "HEAD" + index, ok := gitQuiet(checkout, "rev-parse", "--path-format=absolute", "--git-path", "index") + if !ok { + return clean + } + dir, err := os.MkdirTemp("", "lich-index-") + if err != nil { + slog.Warn("project: snapshot a checkout", "checkout", checkout, "err", err) + return clean + } + defer func() { _ = os.RemoveAll(dir) }() + raw, err := os.ReadFile(strings.TrimRight(index, "\r\n")) + if err != nil { + return clean + } + private := filepath.Join(dir, "index") + if err := os.WriteFile(private, raw, 0o600); err != nil { + slog.Warn("project: snapshot a checkout", "checkout", checkout, "err", err) + return clean + } + cmd := command("git", "-C", checkout, "stash", "create") + cmd.Env = append(cmd.Env, "GIT_INDEX_FILE="+private) + out, err := cmd.Output() + if snapshot := strings.TrimSpace(string(out)); err == nil && snapshot != "" { + return snapshot + } + return clean +} + +func nulPaths(out string) []string { + return strings.FieldsFunc(out, func(r rune) bool { return r == 0 }) +} diff --git a/internal/project/mergecollision_test.go b/internal/project/mergecollision_test.go new file mode 100644 index 000000000..571bfd3b2 --- /dev/null +++ b/internal/project/mergecollision_test.go @@ -0,0 +1,131 @@ +package project + +import ( + "os" + "path/filepath" + "slices" + "strings" + "testing" +) + +// landed is a clone with two worktrees, ours and theirs, off one base that +// holds shared.txt and calm.txt. theirs changed both and added new.txt. +type landed struct { + ours string + oursGit, origin func(args ...string) string + commit, originAt string +} + +func landTheirs(t *testing.T, merge ...string) landed { + t.Helper() + clone, cloneGit, originGit := initClone(t) + originAt := originGit("rev-parse", "--show-toplevel") + commitFile(t, originAt, originGit, "shared.txt", "one\n", "shared") + commitFile(t, originAt, originGit, "calm.txt", "one\n", "calm") + cloneGit("fetch", "origin") + wt := t.TempDir() + ours, theirs := filepath.Join(wt, "ours"), filepath.Join(wt, "theirs") + cloneGit("worktree", "add", "-b", "ours", ours, "origin/main") + cloneGit("worktree", "add", "-b", "theirs", theirs, "origin/main") + theirsGit := gitIn(t, theirs) + commitFile(t, theirs, theirsGit, "shared.txt", "theirs\n", "shared") + commitFile(t, theirs, theirsGit, "calm.txt", "theirs\n", "calm") + commitFile(t, theirs, theirsGit, "new.txt", "theirs\n", "new") + commit := New(nil).HeadCommit(theirs) + originGit("fetch", clone, "theirs") + originGit(append([]string{"merge"}, append(merge, "FETCH_HEAD")...)...) + if slices.Contains(merge, "--squash") { + originGit("commit", "-m", "squashed") + } + return landed{ours: ours, oursGit: gitIn(t, ours), origin: originGit, commit: commit, originAt: originAt} +} + +func TestMergeCollisions(t *testing.T) { + t.Parallel() + ways := map[string][]string{ + "squash": {"--squash"}, + "merge commit": {"--no-ff", "-m", "merged"}, + "fast-forward": {"--ff-only"}, + } + cases := map[string]struct { + work func(t *testing.T, l landed) + want []string + }{ + "no work of its own": {func(*testing.T, landed) {}, nil}, + "a committed change": {func(t *testing.T, l landed) { commitFile(t, l.ours, l.oursGit, "shared.txt", "ours\n", "ours") }, []string{"shared.txt"}}, + "an uncommitted change": {func(t *testing.T, l landed) { writeWork(t, l.ours, "shared.txt", "ours\n") }, []string{"shared.txt"}}, + "an untracked file": {func(t *testing.T, l landed) { writeWork(t, l.ours, "new.txt", "ours\n") }, []string{"new.txt"}}, + "the same change": {func(t *testing.T, l landed) { writeWork(t, l.ours, "shared.txt", "theirs\n") }, nil}, + "a file of its own": {func(t *testing.T, l landed) { writeWork(t, l.ours, "mine.txt", "ours\n") }, nil}, + "pulled, then changed further": {func(t *testing.T, l landed) { + l.oursGit("pull", "origin", "main") + writeWork(t, l.ours, "shared.txt", "ours\n") + }, nil}, + } + for way, args := range ways { + for name, c := range cases { + t.Run(way+"/"+name, func(t *testing.T) { + t.Parallel() + l := landTheirs(t, args...) + c.work(t, l) + before := l.oursGit("status", "--porcelain") + if got := New(nil).MergeCollisions(l.ours, l.commit, "main"); !slices.Equal(got, c.want) { + t.Fatalf("collisions = %v, want %v", got, c.want) + } + if after := l.oursGit("status", "--porcelain"); after != before { + t.Fatalf("the checkout changed: %q, was %q", after, before) + } + if stashes := l.oursGit("stash", "list"); stashes != "" { + t.Fatalf("left a stash: %q", stashes) + } + }) + } + } +} + +// A conflict with somebody else's work on the base is not this merge's news. +func TestMergeCollisionsLeaveOutFilesTheBranchDidNotChange(t *testing.T) { + t.Parallel() + l := landTheirs(t, "--squash") + commitFile(t, l.originAt, l.origin, "README.md", "somebody else\n", "other") + commitFile(t, l.ours, l.oursGit, "README.md", "ours\n", "ours") + writeWork(t, l.ours, "calm.txt", "ours\n") + if got := New(nil).MergeCollisions(l.ours, l.commit, "main"); !slices.Equal(got, []string{"calm.txt"}) { + t.Fatalf("collisions = %v, want calm.txt alone", got) + } +} + +func TestMergeCollisionsSayNothingOfACheckoutAlreadyMerging(t *testing.T) { + t.Parallel() + l := landTheirs(t, "--squash") + commitFile(t, l.ours, l.oursGit, "shared.txt", "ours\n", "ours") + l.oursGit("fetch", "origin") + if _, err := runGit(l.ours, "-c", "user.name=t", "-c", "user.email=t@t", "merge", "origin/main"); err == nil { + t.Fatal("the merge was clean, want it stopped on shared.txt") + } + if got := New(nil).MergeCollisions(l.ours, l.commit, "main"); got != nil { + t.Fatalf("collisions = %v, want none", got) + } +} + +func TestMergeCollisionsSayNothingOfAnotherRepository(t *testing.T) { + t.Parallel() + l := landTheirs(t, "--squash") + other, _ := initRepo(t) + writeWork(t, other, "shared.txt", "ours\n") + for _, checkout := range []string{other, t.TempDir()} { + if got := New(nil).MergeCollisions(checkout, l.commit, "main"); got != nil { + t.Errorf("collisions at %s = %v, want none", checkout, got) + } + } + if got := New(nil).HeadCommit(t.TempDir()); got != "" || strings.TrimSpace(l.commit) == "" { + t.Errorf("HeadCommit outside a repository = %q, of the branch = %q", got, l.commit) + } +} + +func writeWork(t *testing.T, dir, name, content string) { + t.Helper() + if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil { + t.Fatal(err) + } +} diff --git a/internal/prompt/catalog.go b/internal/prompt/catalog.go index 13ee16b91..f4097b853 100644 --- a/internal/prompt/catalog.go +++ b/internal/prompt/catalog.go @@ -60,6 +60,9 @@ type Catalog struct { // GitLab numbers !N. MergeNotice string MergeNoticeGitLab string + // MergeConflict follows either merge notice, on its own line, for an agent + // whose work that merge conflicts with: %[1]s is the files, %[2]s the base. + MergeConflict string // LateNotice and OnTimeNotice sum up a scheduled prompt come due: %[1]s is // when it was parked for, %[2]s how late it is. LateNotice string diff --git a/internal/prompt/en.go b/internal/prompt/en.go index 2ef09a57c..917019490 100644 --- a/internal/prompt/en.go +++ b/internal/prompt/en.go @@ -48,6 +48,7 @@ var en = Catalog{ MergeNotice: "Pull request #%[1]d %[2]q was merged into %[3]s.", MergeNoticeGitLab: "Merge request !%[1]d %[2]q was merged into %[3]s.", + MergeConflict: "That merge conflicts with the work in this checkout in: %[1]s. Before going on, read what it changed there with `git diff HEAD...origin/%[2]s -- `: part of what you are doing may already be done. Do not merge or rebase in the middle of your task because of this notice alone.", LateNotice: "Scheduled for %[1]s, delivered %[2]s late.", LateMinutes: Plural{One: "%d minute", Other: "%d minutes"}, LateHours: Plural{One: "%d hour", Other: "%d hours"}, diff --git a/internal/prompt/es.go b/internal/prompt/es.go index 4c0fbc3bc..5ab8a2971 100644 --- a/internal/prompt/es.go +++ b/internal/prompt/es.go @@ -43,6 +43,7 @@ var es = Catalog{ MergeNotice: "El pull request #%[1]d %[2]q se fusionó en %[3]s.", MergeNoticeGitLab: "El merge request !%[1]d %[2]q se fusionó en %[3]s.", + MergeConflict: "Esa fusión entra en conflicto con el trabajo de este checkout en: %[1]s. Antes de continuar, lee lo que cambió ahí con `git diff HEAD...origin/%[2]s -- `: parte de lo que estás haciendo puede estar ya hecha. No hagas merge ni rebase a mitad de la tarea solo por este aviso.", LateNotice: "Programado para %[1]s, entregado con %[2]s de retraso.", LateMinutes: Plural{One: "%d minuto", Other: "%d minutos"}, LateHours: Plural{One: "%d hora", Other: "%d horas"}, diff --git a/internal/prompt/ja.go b/internal/prompt/ja.go index 5bc5c0bb5..41eacd488 100644 --- a/internal/prompt/ja.go +++ b/internal/prompt/ja.go @@ -43,6 +43,7 @@ var ja = Catalog{ MergeNotice: "プルリクエスト #%[1]d %[2]q が %[3]s にマージされました。", MergeNoticeGitLab: "マージリクエスト !%[1]d %[2]q が %[3]s にマージされました。", + MergeConflict: "このマージは、このチェックアウトでの作業と次のファイルで競合します: %[1]s。作業を続ける前に `git diff HEAD...origin/%[2]s -- ` で変更内容を確認してください。進めている作業の一部がすでに済んでいるかもしれません。この通知だけを理由に、タスクの途中でマージやリベースをしないでください。", LateNotice: "%[1]s に予定されていたものが、%[2]s 遅れて届きました。", LateMinutes: Plural{One: "%d 分", Other: "%d 分"}, LateHours: Plural{One: "%d 時間", Other: "%d 時間"}, diff --git a/internal/prompt/ko.go b/internal/prompt/ko.go index 91122c8ab..6fd1c65ad 100644 --- a/internal/prompt/ko.go +++ b/internal/prompt/ko.go @@ -41,6 +41,7 @@ var ko = Catalog{ MergeNotice: "풀 리퀘스트 #%[1]d %[2]q이(가) %[3]s에 병합되었습니다.", MergeNoticeGitLab: "병합 요청 !%[1]d %[2]q이(가) %[3]s에 병합되었습니다.", + MergeConflict: "이 병합은 다음 파일에서 이 체크아웃의 작업과 충돌합니다: %[1]s. 작업을 이어 가기 전에 `git diff HEAD...origin/%[2]s -- `로 무엇이 바뀌었는지 확인하세요. 하고 있는 일의 일부가 이미 끝났을 수 있습니다. 이 알림만을 이유로 작업 도중에 병합하거나 리베이스하지 마세요.", LateNotice: "%[1]s에 예약되었고, %[2]s 늦게 전달되었습니다.", LateMinutes: Plural{One: "%d분", Other: "%d분"}, LateHours: Plural{One: "%d시간", Other: "%d시간"}, diff --git a/internal/prompt/pt_br.go b/internal/prompt/pt_br.go index c392c5d42..6c8c35b3f 100644 --- a/internal/prompt/pt_br.go +++ b/internal/prompt/pt_br.go @@ -43,6 +43,7 @@ var ptBR = Catalog{ MergeNotice: "O pull request #%[1]d %[2]q foi mergeado em %[3]s.", MergeNoticeGitLab: "O merge request !%[1]d %[2]q foi mergeado em %[3]s.", + MergeConflict: "Esse merge conflita com o trabalho deste checkout em: %[1]s. Antes de continuar, leia o que ele mudou ali com `git diff HEAD...origin/%[2]s -- `: parte do que você está fazendo pode já estar pronta. Não faça merge nem rebase no meio da tarefa só por causa deste aviso.", LateNotice: "Agendado para %[1]s, entregue com %[2]s de atraso.", LateMinutes: Plural{One: "%d minuto", Other: "%d minutos"}, LateHours: Plural{One: "%d hora", Other: "%d horas"}, diff --git a/internal/prompt/ru.go b/internal/prompt/ru.go index 14e3411ac..71f7f1f38 100644 --- a/internal/prompt/ru.go +++ b/internal/prompt/ru.go @@ -52,6 +52,7 @@ var ru = Catalog{ MergeNotice: "Pull request #%[1]d %[2]q слит в %[3]s.", MergeNoticeGitLab: "Merge request !%[1]d %[2]q слит в %[3]s.", + MergeConflict: "Это слияние конфликтует с работой в этой рабочей копии в файлах: %[1]s. Прежде чем продолжать, посмотрите, что там изменилось, командой `git diff HEAD...origin/%[2]s -- `: часть того, что вы делаете, может быть уже готова. Не выполняйте merge или rebase посреди задачи только из-за этого уведомления.", LateNotice: "Запланировано на %[1]s, доставлено с опозданием на %[2]s.", LateMinutes: Plural{One: "%d минуту", Few: "%d минуты", Many: "%d минут", Other: "%d минуты"}, LateHours: Plural{One: "%d час", Few: "%d часа", Many: "%d часов", Other: "%d часа"}, diff --git a/internal/prompt/zh_cn.go b/internal/prompt/zh_cn.go index f3a3d6e7e..b3d7820de 100644 --- a/internal/prompt/zh_cn.go +++ b/internal/prompt/zh_cn.go @@ -39,6 +39,7 @@ var zhCN = Catalog{ MergeNotice: "拉取请求 #%[1]d %[2]q 已合并到 %[3]s。", MergeNoticeGitLab: "合并请求 !%[1]d %[2]q 已合并到 %[3]s。", + MergeConflict: "这次合并与此 checkout 中的工作在以下文件上有冲突:%[1]s。继续之前,请用 `git diff HEAD...origin/%[2]s -- ` 查看那里改动了什么:你正在做的事情可能有一部分已经完成。不要仅因为这条通知就在任务中途合并或变基。", LateNotice: "原定于 %[1]s 发送,延迟 %[2]s 送达。", LateMinutes: Plural{One: "%d 分钟", Other: "%d 分钟"}, LateHours: Plural{One: "%d 小时", Other: "%d 小时"}, diff --git a/internal/relay/editnote.go b/internal/relay/editnote.go index f0310591c..8d5f740e1 100644 --- a/internal/relay/editnote.go +++ b/internal/relay/editnote.go @@ -47,16 +47,22 @@ type edits struct { } // Touched answers a /session-touched call (docs/hooks/session-touched.md): the -// edit-overlap notes for its session, "" when there is nothing to say. A held -// touch records and answers nothing; its note waits for the next answer. +// merge-conflict and edit-overlap notes for its session, "" when there is +// nothing to say. A held touch records and answers nothing; its note waits for +// the next answer. func (s *Service) Touched(req api.TouchedRequest) string { + s.checkLandings(req.SessionID) if !req.Collect { s.recordEdits(req.SessionID, req.Paths) if req.Hold { return "" } } - return s.takeEditNote(req.SessionID) + notes := s.takeMergeNotes(req.SessionID) + if note := s.takeEditNote(req.SessionID); note != "" { + notes = append(notes, note) + } + return strings.Join(notes, "\n\n") } // recordEdits makes session the last editor of paths, holding an overlap for diff --git a/internal/relay/envelope.go b/internal/relay/envelope.go index 20d511733..9247dcf4b 100644 --- a/internal/relay/envelope.go +++ b/internal/relay/envelope.go @@ -24,16 +24,17 @@ const ( // The topics a notice carries. const ( - TopicChecksFailed = "checks-failed" - TopicChecksPassed = "checks-passed" - TopicReview = "review" - TopicScheduled = "scheduled" - TopicUsageReset = "usage-reset" - TopicCompacted = "compacted" - TopicUnanswered = "unanswered" - TopicLoop = "loop" - TopicHandoff = "handoff" - TopicEditOverlap = "edit-overlap" + TopicChecksFailed = "checks-failed" + TopicChecksPassed = "checks-passed" + TopicReview = "review" + TopicScheduled = "scheduled" + TopicUsageReset = "usage-reset" + TopicCompacted = "compacted" + TopicUnanswered = "unanswered" + TopicLoop = "loop" + TopicHandoff = "handoff" + TopicEditOverlap = "edit-overlap" + TopicMergeConflict = "merge-conflict" ) // How a task's answer is taken. diff --git a/internal/relay/envelope_test.go b/internal/relay/envelope_test.go index c965c7477..3f9c9183b 100644 --- a/internal/relay/envelope_test.go +++ b/internal/relay/envelope_test.go @@ -49,6 +49,8 @@ func fixtureEnvelopes() map[string]string { fmt.Sprintf(prompt.For(en).LateNotice, "09:00", lateBy(en, 4*time.Minute)), "Rebase on main and run the gate.").String(), "notice: edit overlap": editEnvelope(en, store.Session{ID: "c41f", Label: "Docs sweep"}, editGroup{paths: []string{"/src/lich/internal/relay/conn.go"}, newest: time.Unix(0, 0)}, "send_to_session", time.Unix(240, 0)).String(), + "notice: merge conflict": mergeConflictEnvelope(en, api.AnnounceMergeOptions{Number: 1210, Title: "fix(relay): handshake race", + Branch: "fix-412-handshake", Base: "main"}, []string{"internal/relay/conn.go", "internal/relay/relay.go"}).String(), "escaping: attributes escaped, element text verbatim": outcomeEnvelope(en, escaped, true, true).String(), "two envelopes in one message, oldest first, one blank line apart": newsMessage(en, []*inboxEntry{fixed, entry(StatusExpired, "")}, []*inboxEntry{fixed}, true), } diff --git a/internal/relay/merged.go b/internal/relay/merged.go index 7754ea82e..009724980 100644 --- a/internal/relay/merged.go +++ b/internal/relay/merged.go @@ -18,7 +18,8 @@ import ( // waiting on a merge, which a later session reads back as true long after the // checkout is gone. The session that opened one of those agents hears it too, // wherever it runs: it handed the work out and keeps the same kind of notes on -// it. +// it. The agents of other checkouts hear only of a merge their work conflicts +// with, and not here (mergenote.go). // // Only provider sessions hear it: a terminal card in the same checkout is a // shell, where a typed notice would run as a command. A card with no process @@ -36,6 +37,7 @@ func (s *Service) AnnounceMerge(ctx context.Context, opts api.AnnounceMergeOptio if !s.firstToldOf(opts.Checkout, opts.Number) { return api.None{}, nil } + s.recordLanding(projects, opts) lang := s.lang() message := mergedEnvelope(lang, opts.Forge, opts.Number, opts.Title, opts.Branch, opts.Base).String() for _, sess := range s.mergeAudience(projects, opts.Checkout) { diff --git a/internal/relay/mergenote.go b/internal/relay/mergenote.go new file mode 100644 index 000000000..9c33852c6 --- /dev/null +++ b/internal/relay/mergenote.go @@ -0,0 +1,104 @@ +package relay + +import ( + "fmt" + "strings" + "sync" + + "github.com/lichdotdev/lich/api" + "github.com/lichdotdev/lich/internal/prompt" + "github.com/lichdotdev/lich/internal/store" +) + +// A merge is told to the agents of the repository's other checkouts whose work +// it conflicts with. Nothing is typed, since a message would start a turn in +// an idle session: the note rides the answer to a touch, as an edit-overlap one +// does. The conflicts are read when the session next writes, not at the +// merge, so a session that went on meanwhile hears of its work as it is; and +// behind the touch, since they fetch and the hook gives up after a second, so +// the note is the answer to a later one. + +// landing is a merge one session has yet to be checked against. +type landing struct { + api.AnnounceMergeOptions + // commit is the merged branch's, checkout the one the session runs in. + commit, checkout string +} + +// mergeNotes is in memory only: a restart forgets every landing and note. +type mergeNotes struct { + mu sync.Mutex + landed map[string][]landing + ready map[string][]string +} + +// SetMergeCollisions wires what reads a merge against the other checkouts +// (internal/project): head is the commit checked out at a path, and collisions +// the files checkout's work conflicts with base in, now that commit merged +// there. Startup wiring; without it only the merged checkout hears of a merge. +func (s *Service) SetMergeCollisions(head func(path string) string, collisions func(checkout, commit, base string) []string) { + s.headCommit, s.mergeCollisions = head, collisions +} + +// recordLanding leaves the merge for every live agent outside its checkout. +func (s *Service) recordLanding(projects []store.Project, opts api.AnnounceMergeOptions) { + if s.mergeCollisions == nil { + return + } + commit := s.headCommit(opts.Checkout) + if commit == "" { + return + } + for _, p := range projects { + for _, sess := range p.Sessions { + checkout := sessionCwd(sess.Path, p.Path) + if checkout == opts.Checkout || !s.runsAgent(sess.ID, sess.Kind) { + continue + } + s.merges.mu.Lock() + s.merges.landed[sess.ID] = append(s.merges.landed[sess.ID], landing{opts, commit, checkout}) + s.merges.mu.Unlock() + } + } +} + +// checkLandings reads, behind the call, the merges session was left against its +// work, each once. +func (s *Service) checkLandings(session string) { + s.merges.mu.Lock() + landed := s.merges.landed[session] + delete(s.merges.landed, session) + s.merges.mu.Unlock() + if len(landed) == 0 { + return + } + go func() { + for _, l := range landed { + files := s.mergeCollisions(l.checkout, l.commit, l.Base) + if len(files) == 0 { + continue + } + note := mergeConflictEnvelope(s.lang(), l.AnnounceMergeOptions, files).String() + s.merges.mu.Lock() + s.merges.ready[session] = append(s.merges.ready[session], note) + s.merges.mu.Unlock() + } + }() +} + +func (s *Service) takeMergeNotes(session string) []string { + s.merges.mu.Lock() + defer s.merges.mu.Unlock() + notes := s.merges.ready[session] + delete(s.merges.ready, session) + return notes +} + +func mergeConflictEnvelope(lang prompt.Lang, opts api.AnnounceMergeOptions, files []string) Envelope { + text := prompt.For(lang) + merged := fmt.Sprintf(forgeText(opts.Forge, text.MergeNotice, text.MergeNoticeGitLab), opts.Number, sanitize(opts.Title), opts.Base) + conflict := fmt.Sprintf(text.MergeConflict, sanitize(strings.Join(files, ", ")), opts.Base) + env := noticeEnvelope(TopicMergeConflict, merged+"\n"+conflict, "") + env.PR, env.Branch = opts.Number, opts.Branch + return env +} diff --git a/internal/relay/mergenote_test.go b/internal/relay/mergenote_test.go new file mode 100644 index 000000000..498c50dbc --- /dev/null +++ b/internal/relay/mergenote_test.go @@ -0,0 +1,117 @@ +package relay + +import ( + "strings" + "testing" + "time" + + "github.com/lichdotdev/lich/api" + "github.com/lichdotdev/lich/internal/prompt" + "github.com/lichdotdev/lich/internal/providers" + "github.com/lichdotdev/lich/internal/store" +) + +func announceLanding(t *testing.T, svc *Service) { + t.Helper() + opts := api.AnnounceMergeOptions{Checkout: "/wt/feat", Number: 42, Title: "Add merge notice", Branch: "feat/merge", Base: "main"} + if _, err := svc.AnnounceMerge(t.Context(), opts); err != nil { + t.Fatalf("AnnounceMerge: %v", err) + } +} + +// awaitNote touches until a note comes back: the merge is read behind the first. +func awaitNote(svc *Service, req api.TouchedRequest) string { + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + if note := svc.Touched(req); note != "" { + return note + } + time.Sleep(time.Millisecond) + } + return "" +} + +// Every provider's session hears it through its touched hook, at once or, where +// the hook cannot show text, at the next collect; none is typed at. +func TestAMergeThatConflictsIsToldOnTheNextTouchOfEveryProvider(t *testing.T) { + t.Parallel() + for _, provider := range providers.Registry { + for mode, hold := range map[string]bool{"answered": false, "held": true} { + t.Run(provider.ID+"/"+mode, func(t *testing.T) { + t.Parallel() + sessions := fakeSessions{projects: []store.Project{{Path: "/src/lich", Sessions: []store.Session{ + {ID: "b", Kind: "claude", Path: "/wt/feat"}, + {ID: "a", Kind: provider.ID, Path: "/wt/fix"}, + }}}} + term := newFakeTerminal("a", "b") + svc := newRelay(sessions, term, nil) + svc.SetMergeCollisions(func(string) string { return "c0ffee" }, func(checkout, commit, base string) []string { + if checkout != "/wt/fix" || commit != "c0ffee" || base != "main" { + t.Errorf("read %s against %s on %s", checkout, commit, base) + } + return []string{"foo.go"} + }) + announceLanding(t, svc) + if note := svc.Touched(api.TouchedRequest{SessionID: "a", Hold: hold}); hold && note != "" { + t.Fatalf("a held touch answered %q", note) + } + note := awaitNote(svc, api.TouchedRequest{SessionID: "a", Collect: hold}) + for _, want := range []string{`topic="merge-conflict"`, `pr="42"`, "#42", "foo.go", "origin/main"} { + if !strings.Contains(note, want) { + t.Errorf("note %q is missing %q", note, want) + } + } + if again := svc.Touched(api.TouchedRequest{SessionID: "a"}); again != "" { + t.Errorf("told twice: %q", again) + } + if got := term.written("a"); got != "" { + t.Errorf("typed at the session: %q", got) + } + }) + } + } +} + +// The merged checkout's own agents, shells and parked cards are left no merge, +// and one that conflicts with nothing is read once and never told. +func TestAMergeIsReadOnlyForLiveAgentsElsewhere(t *testing.T) { + t.Parallel() + svc := newRelay(merging(), newFakeTerminal("root", "agent", "shell", "other"), nil) + read := make(chan string, 8) + svc.SetMergeCollisions(func(string) string { return "c0ffee" }, func(checkout, _, _ string) []string { + read <- checkout + return nil + }) + announceLanding(t, svc) + if len(svc.merges.landed) != 2 || len(svc.merges.landed["root"]) != 1 || len(svc.merges.landed["other"]) != 1 { + t.Fatalf("landed = %v, want root and other", svc.merges.landed) + } + svc.Touched(api.TouchedRequest{SessionID: "other"}) + if got := <-read; got != "/wt/fix" { + t.Fatalf("read %s, want /wt/fix", got) + } + if note := svc.Touched(api.TouchedRequest{SessionID: "other"}); note != "" || len(svc.merges.landed["other"]) != 0 { + t.Fatalf("note = %q, landed = %v; want nothing left", note, svc.merges.landed["other"]) + } +} + +func TestAMergedCheckoutWithNoCommitLeavesNothingToRead(t *testing.T) { + t.Parallel() + svc := newRelay(merging(), newFakeTerminal("other"), nil) + svc.SetMergeCollisions(func(string) string { return "" }, func(string, string, string) []string { return []string{"foo.go"} }) + announceLanding(t, svc) + if len(svc.merges.landed) != 0 { + t.Fatalf("landed = %v, want none", svc.merges.landed) + } +} + +func TestAGitLabMergeConflictNamesTheMergeRequest(t *testing.T) { + t.Parallel() + for _, lang := range prompt.Langs { + opts := api.AnnounceMergeOptions{Number: 42, Title: "Title \x1b[201~", Branch: "b", Base: "main", Forge: api.ForgeGitLab} + note := mergeConflictEnvelope(lang, opts, []string{"a.go", "b.go"}).String() + if !strings.Contains(note, "!42") || !strings.Contains(note, "a.go, b.go") || strings.Contains(note, "\x1b") { + t.Errorf("%s: note = %q", lang, note) + } + } +} diff --git a/internal/relay/relay.go b/internal/relay/relay.go index 7977beeba..14a76bb9a 100644 --- a/internal/relay/relay.go +++ b/internal/relay/relay.go @@ -485,6 +485,11 @@ type Service struct { // edits is who last edited each path, for the edit-overlap notice // (editnote.go). edits edits + // merges is the merges other checkouts' sessions are still to be told of + // (mergenote.go), read through headCommit and mergeCollisions. + merges mergeNotes + headCommit func(path string) string + mergeCollisions func(checkout, commit, base string) []string } // Plugins is what the relay needs to know about the companion plugin @@ -521,6 +526,7 @@ func New(sessions Sessions, term Terminal, events Events) *Service { turnTools: make(map[string]turnTools), streaks: make(map[sessionPair]int), edits: edits{last: make(map[string]edit), held: make(map[string][]overlap)}, + merges: mergeNotes{landed: make(map[string][]landing), ready: make(map[string][]string)}, sessions: sessions, term: term, events: events, diff --git a/main.go b/main.go index 25ffadc15..11e89c3f0 100644 --- a/main.go +++ b/main.go @@ -629,6 +629,7 @@ func registerServices(db *store.Service, term *terminal.Service, chats *chat.Ser // of its own. proj.SetAgentCheckouts(rl.AgentCheckouts) proj.SetAnnounceMerge(rl.AnnounceMerge) + rl.SetMergeCollisions(proj.HeadCommit, proj.MergeCollisions) proj.SetPullRequestWatch(rl.WatchesCheckout, rl.ReadPullRequest) go proj.RunBranchPRWatch() // A turn a usage limit ended is picked up again once it resets, through From 5994f152efcfc6b2ef9b9ccae8390aff8ad7723b Mon Sep 17 00:00:00 2001 From: omartelo Date: Thu, 3 Dec 2026 15:27:22 -0300 Subject: [PATCH 2/3] test(relay): keep the answer of the first touch, which may already carry the note Dropping it asserted an order the contract never promised: 7 failures in 9000 runs of each case, 0 after. --- internal/relay/mergenote_test.go | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/internal/relay/mergenote_test.go b/internal/relay/mergenote_test.go index 498c50dbc..16e673627 100644 --- a/internal/relay/mergenote_test.go +++ b/internal/relay/mergenote_test.go @@ -19,7 +19,8 @@ func announceLanding(t *testing.T, svc *Service) { } } -// awaitNote touches until a note comes back: the merge is read behind the first. +// awaitNote touches until a note comes back: the merge is read behind the first touch, +// whose own answer carries the note when the read wins the race. func awaitNote(svc *Service, req api.TouchedRequest) string { deadline := time.Now().Add(2 * time.Second) for time.Now().Before(deadline) { @@ -52,8 +53,10 @@ func TestAMergeThatConflictsIsToldOnTheNextTouchOfEveryProvider(t *testing.T) { return []string{"foo.go"} }) announceLanding(t, svc) - if note := svc.Touched(api.TouchedRequest{SessionID: "a", Hold: hold}); hold && note != "" { - t.Fatalf("a held touch answered %q", note) + if hold { + if note := svc.Touched(api.TouchedRequest{SessionID: "a", Hold: true}); note != "" { + t.Fatalf("a held touch answered %q", note) + } } note := awaitNote(svc, api.TouchedRequest{SessionID: "a", Collect: hold}) for _, want := range []string{`topic="merge-conflict"`, `pr="42"`, "#42", "foo.go", "origin/main"} { From c933239e3f2eb3dba2af8082bcf0cba8d247fd33 Mon Sep 17 00:00:00 2001 From: omartelo Date: Thu, 3 Dec 2026 15:48:59 -0300 Subject: [PATCH 3/3] fix(chat): a panel opened during another's read loads once that one lands The read of the second panel was skipped while the first ran, and the first's answer was dropped, so the second stayed on Loading. The macos runner was slow enough to hit it in TestPermissionsOpenOnTheAllowRules. --- CHANGELOG.md | 1 + native/cmd/lich-native/chat_tools.go | 10 ++++++++- native/cmd/lich-native/chat_tools_test.go | 25 ++++++++++++++++++++++- 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bd1974108..5670d4371 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,6 +52,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **A chat whose agent cannot start no longer floods its backend.** With the agent's CLI missing, on this computer or a server, the window asked for the conversation about ten times a second; it now asks once, and again when the session changes. - **Inline code keeps its padding when it ends a line.** In some widths the code at the end of a line in a chat lost the room after it, and its background stopped at the last letter. - **Plan usage that could not be read comes back within about a minute.** One dropped connection, such as lich opening before the network was up, used to blank it for five minutes. +- **A chat panel opened while another is still loading no longer stays on Loading.** Opening `/permissions` right after `/mcp`, or any two of these panels, loads the second one as soon as the first answers. ## [0.94.0] - 2026-11-29 diff --git a/native/cmd/lich-native/chat_tools.go b/native/cmd/lich-native/chat_tools.go index 5dda84d61..6a6251fff 100644 --- a/native/cmd/lich-native/chat_tools.go +++ b/native/cmd/lich-native/chat_tools.go @@ -46,6 +46,9 @@ type chatTools struct { plugins api.ChatPluginList loaded bool fetching bool + // again is the panel that asked for a read while one was running, which + // may be another panel's or older than what asked. + again string // gen counts the reads that landed, for what is kept from one. gen int plug chatPlugins @@ -143,6 +146,7 @@ func (u *window) fetchTools(p *chatPane, id string) { t.mu.Lock() kind := t.kind if t.fetching || kind == "" { + t.again = kind t.mu.Unlock() return } @@ -176,7 +180,8 @@ func (u *window) fetchTools(p *chatPane, id string) { plugins, err = u.client.For(id).ChatPlugins(u.ctx, id) } t.mu.Lock() - t.fetching = false + again := t.again != "" && t.again == t.kind + t.fetching, t.again = false, "" if err == nil && t.kind == kind { t.mcp, t.skills, t.plugins, t.loaded = mcp, skills, plugins, true t.set.perms, t.set.hooks = perms, hooks @@ -184,6 +189,9 @@ func (u *window) fetchTools(p *chatPane, id string) { t.gen++ } t.mu.Unlock() + if again { + u.fetchTools(p, id) + } u.chatFailed(err) u.model.invalidate() }() diff --git a/native/cmd/lich-native/chat_tools_test.go b/native/cmd/lich-native/chat_tools_test.go index d3560ed7f..8ebef13f2 100644 --- a/native/cmd/lich-native/chat_tools_test.go +++ b/native/cmd/lich-native/chat_tools_test.go @@ -39,6 +39,11 @@ func toolsFrames(t *testing.T, command string) (*window, *frameRig, *chatBackend u.model.chat.history("s1", []backend.ChatItem{{ID: "u1", Kind: api.ItemUser, Turn: 1, Text: "go"}}) r.settle(t) p := u.chats.pane("s1") + r.reading = func() bool { + p.tools.mu.Lock() + defer p.tools.mu.Unlock() + return p.tools.fetching + } typeIn(r, p, command) // the first Enter completes the command in the slash list, the second sends it r.press(key.NameReturn) @@ -47,9 +52,13 @@ func toolsFrames(t *testing.T, command string) (*window, *frameRig, *chatBackend return u, r, f, p } -// toolsSettle lets the read land and the frames draw it. +// toolsSettle lets an action start its read, waits for the read to land however +// slow the machine is, and lets the frames draw it. func toolsSettle(r *frameRig) { time.Sleep(50 * time.Millisecond) + for deadline := time.Now().Add(settleTimeout); r.reading != nil && r.reading() && time.Now().Before(deadline); { + time.Sleep(time.Millisecond) + } r.frames(3) } @@ -69,6 +78,20 @@ func TestMCPOpensTheServersInsteadOfSending(t *testing.T) { } } +// A panel opened while another's read is still running reads its own once that +// one lands, instead of staying on Loading. +func TestAPanelOpenedDuringAnothersReadStillLoads(t *testing.T) { + u, r, f, p := toolsFrames(t, "/mcp") + f.mu.Lock() + f.answers[api.ChatPermissions.Name] = toolsRules + p.tools.open(chatMCPCommand) + u.fetchTools(p, "s1") + p.tools.open(chatPermissionsCommand) + u.fetchTools(p, "s1") + f.mu.Unlock() + r.waitFor(t, "Bash(npm run *)") +} + // A server opens on a click with what can be done to it; Escape goes back to // the list and then shuts the panel. func TestAServerOpensAndEscapeGoesBack(t *testing.T) {