From 56573c19ed346da06e203269aa054c17317558d9 Mon Sep 17 00:00:00 2001 From: mubeda <1380447+mubeda@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:51:26 -0300 Subject: [PATCH 001/242] docs(plans): plan for Files undo, remote branch delete, Antigravity terminal and View PR Triage of issues #397 to #400, the spec derived from them, a five-phase plan with its two Codex reviews, and the Antigravity CLI research. Co-Authored-By: Claude Fable 5.2 --- .../execute-plan.md | 99 ++++++++++ .../phases/PHASE-01-files-undo-shortcuts.md | 99 ++++++++++ .../PHASE-02-git-manager-remote-delete.md | 103 +++++++++++ .../phases/PHASE-03-antigravity-terminal.md | 128 +++++++++++++ .../phases/PHASE-04-integration.md | 63 +++++++ .../phases/PHASE-05-view-pr-panel.md | 40 ++++ .../plan.md | 172 ++++++++++++++++++ .../progress.md | 33 ++++ .../research-antigravity.md | 76 ++++++++ .../reviews/plan-review-1.md | 82 +++++++++ .../reviews/plan-review-2.md | 81 +++++++++ .../spec.md | 125 +++++++++++++ .../triage.md | 9 + 13 files changed, 1110 insertions(+) create mode 100644 docs/plans/2026-11-20-undo-remote-delete-antigravity/execute-plan.md create mode 100644 docs/plans/2026-11-20-undo-remote-delete-antigravity/phases/PHASE-01-files-undo-shortcuts.md create mode 100644 docs/plans/2026-11-20-undo-remote-delete-antigravity/phases/PHASE-02-git-manager-remote-delete.md create mode 100644 docs/plans/2026-11-20-undo-remote-delete-antigravity/phases/PHASE-03-antigravity-terminal.md create mode 100644 docs/plans/2026-11-20-undo-remote-delete-antigravity/phases/PHASE-04-integration.md create mode 100644 docs/plans/2026-11-20-undo-remote-delete-antigravity/phases/PHASE-05-view-pr-panel.md create mode 100644 docs/plans/2026-11-20-undo-remote-delete-antigravity/plan.md create mode 100644 docs/plans/2026-11-20-undo-remote-delete-antigravity/progress.md create mode 100644 docs/plans/2026-11-20-undo-remote-delete-antigravity/research-antigravity.md create mode 100644 docs/plans/2026-11-20-undo-remote-delete-antigravity/reviews/plan-review-1.md create mode 100644 docs/plans/2026-11-20-undo-remote-delete-antigravity/reviews/plan-review-2.md create mode 100644 docs/plans/2026-11-20-undo-remote-delete-antigravity/spec.md create mode 100644 docs/plans/2026-11-20-undo-remote-delete-antigravity/triage.md diff --git a/docs/plans/2026-11-20-undo-remote-delete-antigravity/execute-plan.md b/docs/plans/2026-11-20-undo-remote-delete-antigravity/execute-plan.md new file mode 100644 index 000000000..21944eb6e --- /dev/null +++ b/docs/plans/2026-11-20-undo-remote-delete-antigravity/execute-plan.md @@ -0,0 +1,99 @@ +# Execute plan: Files undo shortcuts, remote branch delete, Antigravity terminal + +You are about to execute an approved implementation plan. Read this whole file before doing anything. + +- Plan folder: docs/plans/2026-11-20-undo-remote-delete-antigravity +- Spec: docs/plans/2026-11-20-undo-remote-delete-antigravity/spec.md (binding authority; the plan argues from it) +- Planned on: Claude Code, 2026-11-20 +- Plan reviewed by: Codex gpt-6.2-sol, effort high +- Base branch: main +- Recommended mode: Workflow, because round 1 has four phases that own disjoint files + +## 1. Check the plan + +1. Read `progress.md`, `plan.md`, `spec.md` and every file in `phases/`. + Check that `mstack-receive-review` is in this session's skill list (as `mstack-receive-review` or `:mstack-receive-review`), because every review of this run is processed with it. When it is missing, stop before any work and print the install commands: `claude plugin install mstack-receive-review@mstack` (Claude Code) or `codex plugin add mstack-receive-review@mstack` (Codex), after ` plugin marketplace add mubeda/mstack`, or `npx skills add mubeda/mstack --skill mstack-receive-review -g -a -y`; name `mstack-setup`, and say a new session is needed after the install. +2. If `progress.md` says `Plan status: Draft`, stop. Tell the user the plan is not approved and ask them to approve it, or to finish it with `mstack-plan`. +3. Compute the sha256 of `spec.md` (`sha256sum spec.md` or `shasum -a 256 spec.md`). If its first 12 hex digits differ from the `Spec` line of `progress.md`, the spec changed after planning. Stop and ask the user whether to re-plan or continue on the old plan. +4. When `progress.md` has a `Branch` line, continue on that branch. Tasks marked Closed are never redone, but check first that each one's last logged commit is on the branch (`git merge-base --is-ancestor HEAD`). When it is not, because a workflow closed the task and stopped before integrating it, cherry-pick the logged commits from the logged branch. When that branch is gone, set the task back to In progress and log why. +5. A task marked In progress was interrupted. Read its log lines and `git log` on the branch, then finish it from where the evidence stops. + +## 2. Ask the user first + +Before any other work, ask the user these questions in one message, using the host's question tool (in Claude Code `AskUserQuestion`; in Codex a numbered list in chat, then wait). Skip a question only when the user's opening message already answers it. + +1. How should the plan be executed? + (a) Inline. This session implements every task in order, red-green, then gets one cross-vendor review of the whole branch. + (b) Workflow. In Claude Code, the `mstack-codex-review-workflow` skill (Codex reviews). In Codex, the `mstack-claude-review-workflow` skill (Claude reviews). Parallel writer lanes, a cross-vendor review per lane, one integrated branch. + (c) Codex develops. In Claude Code only, the `mstack-claude-pm-codex-dev` skill: Codex writes each phase, and Claude reviews, validates and commits it. + I recommend (b), because round 1 has four phases that own disjoint files. +2. Which reviewer model and effort? I recommend `gpt-6.2-sol` and `high` in Claude Code (the plan's reviewer), or `opus` and `medium` in Codex. +3. May this run commit each finished task to the branch in `progress.md`'s `Branch` line, or, when there is none, create the branch `plan/undo-remote-delete-antigravity` from `main` and commit to it? Pushing and opening a pull request happen only when the user asks. + +## 3. Workflow execution + +1. Load the workflow skill for this host. If it is not installed, give the user its install command and offer inline execution instead. + - Claude Code: `claude plugin marketplace add mubeda/mstack`, then `claude plugin install mstack-codex-review-workflow@mstack`, then start a new session. + - Codex: `codex plugin marketplace add mubeda/mstack`, then `codex plugin add mstack-claude-review-workflow@mstack`, then start a new session. + - Either host, with the skills CLI: ask the user the scope (global or this repository), the method (symlink or copy) and the agents, then run `npx skills add mubeda/mstack --skill -a -y`, adding `-g` for global and `--copy` for copy. + - Choice (c), Claude Code only: `claude plugin marketplace add mubeda/mstack`, then `claude plugin install mstack-claude-pm-codex-dev@mstack`, then start a new session; or with the skills CLI, after the same three questions, `npx skills add mubeda/mstack --skill mstack-claude-pm-codex-dev -a claude-code -y`. It also needs the OpenAI Codex plugin for Claude Code; `mstack-setup` reports and installs it. +2. Give the workflow this plan folder as its work items, and tell it that every review is processed with `mstack-receive-review` without asking the user. It reads the folder as an `mstack-plan` plan: every task is a work item, `progress.md` is its status file, and each task's Skills, Read first and Done when go into the lane brief. +3. The answers to questions 2 and 3 above answer the workflow's own model, effort and commit questions. The workflow still asks its execution mode question, and Workflow mode is recommended when a round has more than one phase. For choice (c), the same two answers answer its reviewer and commit questions; it still asks which developer model and effort to use. + +## 4. Inline execution + +### Rules for the whole run + +1. Work on the branch from question 3. Never work directly on the default branch without the user's consent. +2. Set `Executor: inline` and `Branch: ` in `progress.md`. +3. Keep going without status check-ins. Stop and ask only for: an irreversible or destructive operation, a security-sensitive action, a side effect outside this repository (a push, a publish, a merge), a reviewer model that was rejected (the review step below), or a plan so broken that every way forward is a guess. When the context or the session is running out, stop at a safe point, make sure `progress.md` is current, write a handoff with `mstack-handoff` when it is installed, and give its path; the next session continues from `progress.md` and the handoff. +4. When the plan is wrong in a small way (a renamed function, a moved file), make the smallest change that still satisfies the spec, and log it in `progress.md` as `Ruling: , because . Cost if wrong: .` +5. Never claim a task is done without fresh evidence: run its Done when command in this session, read the whole output and the exit code, and copy the evidence into the log. +6. This session's model does every task, so a task's Tier line does not change it. The tier limits what you delegate: a read-only helper (a search, a log read) runs on the cheapest model this host offers, set explicitly, and no helper runs on a model above the task's tier. In Claude Code that is `Agent` with the model and effort of `haiku` at `low` for a cheap helper and of `sonnet` at `medium` for a standard one. In Codex, pass them as `-m` and `model_reasoning_effort` on the helper run: the cheapest Codex model at `low` effort for a cheap helper, `gpt-6.2-sol` at `medium` for a standard one. A helper started without them runs on this session's model. + +### Per task + +Pick the next task by dependencies. A task is ready when every task in its Depends on line is Closed and every phase its phase depends on is Closed. Among ready tasks, take the lowest phase, then the lowest ID. Skip Closed tasks and tasks marked removed or dropped. A task that depends on a removed or dropped task stays Open, and the final report lists it as blocked. + +1. Set the task to In progress in `progress.md` and add a log line. +2. Load every skill the phase and the task list (in Claude Code with the Skill tool; in Codex by reading the skill's SKILL.md). The plan names skills without a plugin prefix, so use whichever form this host lists, `:` or ``. For a skill this host does not have, follow the task's steps without it and note that in the log. +3. Read every file and source in the phase's and the task's Read first. +4. Follow the steps in order. After each command, compare the output with its `Expected:` line. + - Red-green tasks: see the test fail for the expected reason before writing the code, then see it pass. Do the "prove the test can fail" step, and always restore the code afterwards. + - The output does not match because the code is wrong: debug it before changing anything (load `mstack-diagnose` when it is installed). Never patch the symptom. + - The output does not match because the plan is wrong: apply rule 4. +5. Run the task's Done when command and the phase's lint and format commands. +6. Commit the task's files together with `progress.md`, where the task is now Closed and the log line carries the command, the result and the commit range. + +After a phase's last task, run its Checkpoint and log the result. A failing checkpoint reopens the task that owns the failure. + +### After the last task + +1. Run every check in `plan.md` › End-to-end verification and log each result. +2. Get one cross-vendor review of the whole branch, read-only, with the model and effort from question 2. Write its output outside the repository: `` below is the session's scratch folder when the host has one, otherwise `${TMPDIR:-/tmp}/mstack-plan-undo-remote-delete-antigravity`, created first. Put a path in double quotes in these commands when it contains a space. + - Claude Code (Codex reviews, through the `codex` skill of the skill-codex plugin; timeout at least 600 seconds for `high`, 1200 for `xhigh`, 1800 for `max`): + + Write this prompt to `/review-prompt.md` with your file tool, never with `echo` or a heredoc, so no shell expands anything in it: + + ```text + Read-only code review. Do not edit or run anything that changes files. Review branch against (git diff ...HEAD). The plan is in docs/plans/2026-11-20-undo-remote-delete-antigravity and the spec it implements is docs/plans/2026-11-20-undo-remote-delete-antigravity/spec.md. Check that every requirement in the spec is met, and check correctness, regressions, missing tests and scope. Report each finding with file, line, the failing scenario and how to reproduce it. No findings is a valid result. + ``` + + ```bash + codex exec -m --config model_reasoning_effort="" --sandbox read-only -C - \ + < /review-prompt.md 2> /codex-review.err > /codex-review.md + ``` + + - Codex (Claude reviews, through the `claude-review` skill of the agent-bridges `claude` plugin; it needs network and writes under the home folder, so run it as an approved command): + + ```bash + node "/scripts/claude-companion.mjs" review --wait \ + --cwd --base --scope branch \ + --model --effort /claude-review.md 2> /claude-review.err + ``` + + This review reads the diff, not the spec, so check every requirement against the spec yourself. + + - An empty output or a non-zero exit is never a clean review. Read the end of the `.err` file, fix the cause (a rejected effort: the next lower level, without asking; a rejected model: ask the user once for another model and record it, because the model chosen in question 2 is not consent to another one), and rerun once. If it still fails, the user names no other model, or this host's reviewer is not installed, warn the user that the review will be same-vendor, and run the same review prompt through a fresh, read-only subagent of this host (in Claude Code the `Agent` tool with the model and effort of `opus` at `medium`; in Codex a separate `codex exec -m --config model_reasoning_effort="" --sandbox read-only -C - < /review-prompt.md`, where those two are the model and effort of `gpt-6.2-astra` at `medium`, with the prompt above written to that file, as an approved command because it needs network). Log it as a same-vendor review, and say so in the final report. The fallback never waits on the user; a rejected model is the one thing that does. +3. Process the review with the `mstack-receive-review` skill, without asking the user anything. Verify every finding against the code and reproduce it before accepting it. Fix each real finding with a test you saw fail and then pass. Send an unclear finding back to the reviewer once. Reject a finding that is wrong, cannot be verified, or contradicts a decision the user already made, with the reason. Log every finding and its outcome in `progress.md`. +4. Report to the user: the goal and the outcome in the first line, then the final `progress.md` table, the end-to-end results, every Ruling, every review finding with what happened to it (fixed, rejected and why, deferred), and what was not run and why. Offer to open a pull request. Do not push without the user's request. diff --git a/docs/plans/2026-11-20-undo-remote-delete-antigravity/phases/PHASE-01-files-undo-shortcuts.md b/docs/plans/2026-11-20-undo-remote-delete-antigravity/phases/PHASE-01-files-undo-shortcuts.md new file mode 100644 index 000000000..67da6a245 --- /dev/null +++ b/docs/plans/2026-11-20-undo-remote-delete-antigravity/phases/PHASE-01-files-undo-shortcuts.md @@ -0,0 +1,99 @@ +# Phase 1: Files undo and redo shortcuts + +- Goal: The undo and redo chords and the desktop Edit menu move the Files editor history one step, in the source and rendered views, on macOS, Windows and Linux, with tests and the keybindings doc updated. +- Round: 1 +- Depends on: none +- Owns: `apps/web/src/components/files/**`, `apps/desktop/src-tauri/src/window.rs`, `apps/desktop/e2e/specs/files-undo-shortcuts.e2e.ts`, `apps/desktop/e2e/wdio.conf.ts`, `apps/web/src/components/AppSidebarLayout.tsx` (only on branch B), `docs/user/keybindings.md`, `docs/plans/2026-11-20-undo-remote-delete-antigravity/diagnosis-398.md` +- Must not touch: `apps/web/src/components/gitManager/**`, `apps/web/src/components/chat/**`, `apps/web/src/components/settings/**`, `packages/contracts/**`, `apps/server/**` +- Skills: tdd (a failing test before every behavior change) +- Read first: issue #398 (the report; its cause is marked a guess); `reviews/plan-review-1.md` findings 4 and 6 (the editors already bind the chords, and the native menu differs per platform); `UI.md` (tooltip wording) +- Checkpoint: `BIBCODE_E2E_PROFILER=1 BIBCODE_E2E_SPEC=./specs/files-undo-shortcuts.e2e.ts vp run test:ui:desktop` passes on the packaged build; in the packaged app, a real Cmd+Z or Ctrl+Z after typing in a file removes the typed text. + +Facts this phase starts from, checked on 2026-11-20: + +- The source editor already binds the chords: `@pierre/diffs/dist/editor/command.js` maps `cmdOrCtrl+z` to undo, `cmdOrCtrl+shift+z` to redo, and `ctrl+y` to redo on Windows and Linux. TipTap's history extension binds its own in the rendered view. A new web hook is therefore not assumed. +- The desktop Edit menu uses predefined Undo and Redo items (`apps/desktop/src-tauri/src/window.rs:116-124`). The pinned menu library handles them differently per platform: responder actions on macOS, injected Ctrl+Z / Ctrl+Y on Windows, and no predefined item on GTK. +- The toolbar picks its history at `FilePreviewPanel.tsx:1125-1126`: `activeRichEditor` when set, otherwise `session`. +- The panel also holds an inline comment textarea (`FilePreviewPanel.tsx:677-689`), which must keep its own native undo. + +## Tasks + +### Task 1.1: Reproduce the failure and locate it per platform + +- Satisfies: R5 +- Depends on: none +- Files: create `apps/desktop/e2e/specs/files-undo-shortcuts.e2e.ts`; modify `apps/desktop/e2e/wdio.conf.ts`; create `docs/plans/2026-11-20-undo-remote-delete-antigravity/diagnosis-398.md` +- Interfaces: consumes nothing; produces `diagnosis-398.md`, whose last section gives one disposition per failing cell or group of cells with the same cause (A, B, D, N, U or C, defined in step 5), which Task 1.2 implements +- Skills: mstack-diagnose (reproduce first, one hypothesis at a time); mstack-research (Tauri 2 and its menu library's predefined Undo behavior at the pinned version) +- Read first: `apps/desktop/e2e/specs/files-rich-markdown.e2e.ts` (how a spec opens a file and types); `apps/desktop/e2e/wdio.conf.ts:50-84` (the spec allowlist and `BIBCODE_E2E_SPEC`); `apps/desktop/e2e/support/test-project.ts:1504-1506` (`BIBCODE_E2E_PROFILER`); `docs/testing/macos-desktop.md`, `docs/testing/windows-desktop.md`, `docs/testing/linux-desktop.md` (the packaged runs and labs); `docs/skills/issue-delivery/SKILL.md` (checkpoint before a packaged build) +- Tier: most capable +- TDD: exempt (a diagnosis: it adds a test and a record and changes no product behavior) +- Done when: `diagnosis-398.md` holds the filled matrix of step 4 and a disposition for every failing cell, and `BIBCODE_E2E_SPEC=./specs/files-undo-shortcuts.e2e.ts vp run test:ui:desktop` has been run once with its result recorded; observable in that file + +Steps + +1. [ ] Write `files-undo-shortcuts.e2e.ts` with one case per view (source on a text file, rendered on a `.md` file) and per direction: seed a fresh marker edit, send the platform chord, assert the text and the toolbar's Undo and Redo enabled states. Add a case that Ctrl/Cmd+S still saves, and one that undo in the chat composer still works. Add the spec to the allowlist in `wdio.conf.ts`. +2. [ ] Check `df -h` and `uptime`, take the shared build lock, and build once with `vp run test:ui:desktop:build`. Expected: the packaged app is produced. +3. [ ] Run `BIBCODE_E2E_PROFILER=1 BIBCODE_E2E_SPEC=./specs/files-undo-shortcuts.e2e.ts vp run test:ui:desktop`. Expected: PASS or FAIL, recorded as is. A pass here proves only the injected-key path, because the driver may deliver keys inside the webview. +4. [ ] Fill the matrix in `diagnosis-398.md`, each cell from a freshly seeded edit: platform (macOS, Windows, Linux) by view (source, rendered) by direction (undo, redo) by path (real OS keystroke, Edit menu item, driver key). On macOS send the real keystroke and click the menu item through System Events (`osascript`); on Windows and Linux use the labs the runbooks name. For each failing cell record what reached the editing host: a `keydown`, a cancellable `beforeinput` with `inputType` `historyUndo` or `historyRedo`, or nothing (temporary logging, removed before the task ends). +5. [ ] Give every failing cell, or group of cells with the same cause, one disposition, and write them as the file's last section: + - C: the cell passes. + - N: the menu item does not exist on that platform (the pinned menu library adds no predefined Undo or Redo on GTK). Recorded; not a failure of the menu path. + - A: a cancellable `beforeinput` history event reaches the editing host. Fix: handle that event on the editing host. + - B: nothing reaches the webview, or the event that arrives cannot be cancelled. Fix: custom menu items over the existing `DesktopBridge.onMenuAction` channel, after a reviewed design note. + - D: a `keydown` reaches the editing host but the history does not move. An editor-host defect, fixed in the web code. + - U: the platform or path could not be measured. File a follow-up issue naming the lab that was unavailable and record its number. + Whatever the result, post the matrix as a comment on issue #398. If every measured cell is C or N, also ask the reporter there for the platform and view; Task 1.2 then closes without a code change. +6. [ ] Run `vp check`. Expected: no errors in the files this task created. + +### Task 1.2: Fix the located path and prove it in the packaged app + +- Satisfies: R1, R2, R5 +- Depends on: 1.1 +- Files: modify `apps/web/src/components/files/FilePreviewPanel.tsx`; create `apps/web/src/components/files/useFileHistoryInput.ts` and `apps/web/src/components/files/useFileHistoryInput.test.tsx` (branch A or B); modify `apps/desktop/src-tauri/src/window.rs` and `apps/web/src/components/AppSidebarLayout.tsx` (branch B only); modify `apps/desktop/e2e/specs/files-undo-shortcuts.e2e.ts`; modify `docs/plans/2026-11-20-undo-remote-delete-antigravity/diagnosis-398.md` +- Interfaces: consumes `diagnosis-398.md`; `FileEditingSession.undo(): void` / `.redo(): void` (`fileEditingSession.ts:417-427`); `RichMarkdownEditor.undo()` / `.redo()` (`richMarkdownExtensions.ts:44-48`); on branch B `DesktopBridge.onMenuAction(listener: (action: string) => void): () => void` (`packages/contracts/src/ipc.ts:1394`). Produces `useFileHistoryInput(hostRef: RefObject, history: { undo(): void; redo(): void } | null): void` +- Skills: rust-best-practices (menu wiring on branch B); vercel-react-best-practices (effect and ref rules for the hook); mstack-diagnose (when a fix does not turn its cell green) +- Read first: `docs/plans/2026-11-20-undo-remote-delete-antigravity/diagnosis-398.md` (binding for this task); `apps/web/src/components/files/FilePreviewPanel.tsx:446-470,746-754,892-914,1122-1126`; `apps/web/src/components/files/RichMarkdownView.tsx:47-54`; `apps/web/src/components/AppSidebarLayout.tsx:140` (how menu actions are consumed today) +- Tier: most capable +- TDD: red-green +- Done when: `BIBCODE_E2E_PROFILER=1 BIBCODE_E2E_SPEC=./specs/files-undo-shortcuts.e2e.ts vp run test:ui:desktop` exits 0, and every cell of the `diagnosis-398.md` matrix on a platform whose code changed is re-measured green by its native path and recorded in that file; when every cell was C or N, the recorded matrix and the passing spec close the task with no code change + +Rules for this task + +- Work each disposition of `diagnosis-398.md` on its own: A and D are web fixes with a failing web test first; B is the menu fix. A platform can need more than one. +- For B, the design note comes first, before any code: write `docs/plans/2026-11-20-edit-menu-undo-design.md`, get a Codex and an advisor review, and record them in it. The note gives the exact routing of the menu action for a focused Files editing host, the inline comment textarea, the chat composer (its own Lexical history), a terminal, and a plain input, and names any file outside this phase's ownership that must change, which is handed to the executor. +- After any change to a menu item or accelerator, re-measure every cell of that platform, the passing ones included, and the outside-Files cases (composer, comment textarea, terminal). +- If every cell is C or N, do steps 7 and 8 only. + +Steps + +1. [ ] Write the failing test for the branch chosen. Branch A: in `useFileHistoryInput.test.tsx`, a cancellable `beforeinput` with `inputType` `historyUndo` dispatched on the editing host calls `history.undo` once and is default-prevented; `historyRedo` calls `redo`; the same event on the inline comment textarea or outside the host calls nothing; a `null` history attaches nothing. Branch B: a Rust test in `window.rs` that the Edit menu's Undo and Redo items carry the menu action ids `edit-undo` and `edit-redo` with the platform accelerators, and a web test that the `edit-undo` action calls the Files history once when focus is inside a Files editing host, and otherwise leaves the focused element's own undo untouched (assert it with a real textarea and with the composer's editor). +2. [ ] Run the focused test: `cd apps/web && node ../../scripts/run-local-vp.mjs test run --project unit src/components/files/useFileHistoryInput.test.tsx`, and on branch B also `cargo test -p bibcode-desktop menu`. Expected: FAIL, because the handler or the menu ids do not exist. +3. [ ] Implement the branch. In both, the history is one memoized object built from the exact expressions the toolbar uses at `FilePreviewPanel.tsx:1125-1126`, shared with the toolbar rather than copied, and the handler is scoped to the editing host found through the event's composed path, so the comment textarea is never intercepted. Branch B on a platform where focus is outside Files must fall through to the platform's own undo for that element; if the composer's undo cannot be preserved, stop and log a Ruling instead of shipping. +4. [ ] Disposition B only: confirm the reviewed design note of the Rules above exists before this step's code is written, and update the `DesktopBridge` part of `docs/architecture/overview.md` in the same change. No new bridge command or event is added; the existing string-valued menu action carries the two ids. +5. [ ] Run the focused tests. Expected: PASS. +6. [ ] Prove the test can fail: make the handler return before calling the history, run the focused web command. Expected: FAIL. Restore and run again. Expected: PASS. +7. [ ] Take the build lock, rebuild, and run the Done when command. Expected: PASS, all cases. Then re-measure every previously failing matrix cell by its native path on its platform and record the result in `diagnosis-398.md`. +8. [ ] Run `cargo fmt --all --check` and `cargo clippy -p bibcode-desktop --all-targets -- -D warnings` if `window.rs` changed, and `vp check`. Expected: no errors. A platform that could not be measured is named in the task report with the reason. + +### Task 1.3: Pin the chord behavior in web tests and correct the tooltip + +- Satisfies: R1, R2, R3, R4 +- Depends on: 1.2 +- Files: create `apps/web/src/components/files/fileUndoChords.test.tsx`; modify `apps/web/src/components/files/FileEditorToolbar.tsx`; test `apps/web/src/components/files/FileEditorToolbar.test.tsx`; modify `docs/user/keybindings.md` +- Interfaces: consumes `FilePreviewPanel` and the real Pierre and TipTap editors; produces `redoShortcutLabel(isMac: boolean): string` in `FileEditorToolbar.tsx` +- Skills: vercel-react-best-practices (required review for the changed toolbar); mstack-diagnose (when a baseline test fails in the browser path) +- Read first: `apps/web/src/components/files/FileEditorToolbar.tsx:152-185`; `apps/web/src/components/files/FilePreviewPanel.test.tsx` (how the panel is mounted in tests); `docs/user/keybindings.md` +- Tier: standard +- TDD: red-green +- Done when: `cd apps/web && node ../../scripts/run-local-vp.mjs test run --project unit src/components/files/fileUndoChords.test.tsx src/components/files/FileEditorToolbar.test.tsx` exits 0 + +Steps + +1. [ ] Write `fileUndoChords.test.tsx` against the mounted panel with the real editors: in the source view, after one typed edit, the undo chord restores the text and the toolbar shows Undo disabled and Redo enabled, the redo chord restores the edit, and a chord with nothing to undo changes nothing and is default-prevented; in the rendered view, two edits that land in two history steps (separate them past the history grouping delay with fake timers, and assert as a precondition that two `undo()` calls are needed) lose exactly one step per undo chord, and a formatting edit is undone and redone; Ctrl+Y redoes in both views when the platform is Windows or Linux and does nothing on macOS; a chord typed in the inline comment textarea does not move the file's history; Ctrl/Cmd+S still saves. +2. [ ] Write the failing tooltip test in `FileEditorToolbar.test.tsx`: `redoShortcutLabel(false)` names Shift+Ctrl+Z and Ctrl+Y, `redoShortcutLabel(true)` names Shift+Cmd+Z and does not name Ctrl+Y (it may name other chords that work in both views), and the Redo button's tooltip uses it. +3. [ ] Run the Done when command. Expected: FAIL in the tooltip test. A baseline case of step 1 that fails is a real browser-path defect: reproduce it with `mstack-diagnose`, fix it in the editing host with a test that stays, and log a Ruling in `progress.md`. A baseline case that passes stays as a regression test; that is its purpose. +4. [ ] Implement `redoShortcutLabel` with the platform helper the web app already uses (find it with `rg -n "isMacPlatform|isMac\b" apps/web/src`), and document the three chords in `docs/user/keybindings.md` under the Files editor. +5. [ ] Run the Done when command. Expected: PASS. +6. [ ] Prove the tests can fail: make `redoShortcutLabel` ignore its argument, run the Done when command. Expected: FAIL. Restore and run again. Expected: PASS. +7. [ ] Run `cd apps/web && node ../../scripts/run-local-vp.mjs test run --project unit src/components/files` and `vp check`. Expected: PASS and no errors. Review the toolbar change against `vercel-react-best-practices` and the tooltip against `UI.md`; record both in the task report. diff --git a/docs/plans/2026-11-20-undo-remote-delete-antigravity/phases/PHASE-02-git-manager-remote-delete.md b/docs/plans/2026-11-20-undo-remote-delete-antigravity/phases/PHASE-02-git-manager-remote-delete.md new file mode 100644 index 000000000..5e6725f1f --- /dev/null +++ b/docs/plans/2026-11-20-undo-remote-delete-antigravity/phases/PHASE-02-git-manager-remote-delete.md @@ -0,0 +1,103 @@ +# Phase 2: Git Manager remote branch delete + +- Goal: A remote branch row can be deleted after a confirmation, each remote's default branch is blocked with a reason, sign-in and refusals are visible, and the branch dialogs show the server's block reasons, with tests. +- Round: 1 +- Depends on: none +- Owns: `apps/web/src/components/gitManager/**`, `apps/web/src/components/gitSignIn/**`, `apps/server/src/git/manager/refs.rs`, `apps/server/src/git/manager/operations.rs`, `apps/server/src/git/repository.rs`, `docs/reference/mcp.md` +- Must not touch: `apps/web/src/components/files/**`, `apps/web/src/components/chat/**`, `packages/contracts/**`, `apps/server/src/production/**`, `apps/server/src/provider/**`, `apps/desktop/**`, `docs/user/workspace-ui.md` (phase 4 updates it) +- Skills: tdd (failing test first on both sides) +- Read first: issue #397 (the request and its code references); `reviews/plan-review-1.md` findings 1, 2 and 7; `packages/contracts/src/gitManager.ts:40-75,205-214,251-259` (ref entry, snapshot, the `remote-branch-delete` request with its exact fields); `UI.md` (destructive confirmation and disabled reasons) +- Checkpoint: `cd apps/web && node ../../scripts/run-local-vp.mjs test run --project unit src/components/gitManager src/components/gitSignIn` exits 0 and `cargo test -p bibcode-server refs` exits 0; in the app, a remote row shows Delete and each remote's default branch shows it disabled with a visible reason. + +Facts this phase starts from, checked on 2026-11-20: + +- The server emits the guard operations `checkout`, `delete-branch` and `rename-branch` (`guards.rs:173-198`), while the dialogs look up `branch-delete` and `branch-rename` (`GitManagerBranchDialogs.tsx:316,399`) and the dropdown `branch-checkout` (`GitManagerBranchDropdown.tsx:149`). The request tags (`branch-delete`, `branch-checkout`) are a different thing and stay as they are. +- Remote entries are named `/` (`refs.rs:411`), `is_default` is set for local entries only, and `/HEAD` rows are dropped (`refs.rs:315-346`). +- The sign-in offer of a failed network operation is handled only in `GitManagerPanel.tsx:498-523`; the toolbar's runner (`GitManagerToolbar.tsx:338-371`) records a failure message and revalidates refs. +- The server already has a test that deleting a remote branch leaves its local namesake (`operations.rs:6085-6148`). + +## Tasks + +### Task 2.1: Make the dialogs and the dropdown read the server's guard names + +- Satisfies: R9, R15 +- Depends on: none +- Files: modify `apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.tsx`; test `apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.test.tsx`; modify `apps/web/src/components/gitManager/toolbar/GitManagerBranchDropdown.tsx`; test `apps/web/src/components/gitManager/toolbar/GitManagerBranchDropdown.test.tsx` +- Interfaces: consumes `GitManagerBlockedReason.operation` values `checkout`, `delete-branch`, `rename-branch`; produces the exported constants `GUARD_DELETE_BRANCH = "delete-branch"`, `GUARD_RENAME_BRANCH = "rename-branch"` and `GUARD_CHECKOUT = "checkout"` in a new `apps/web/src/components/gitManager/gitManagerGuardOperations.ts`, which Task 2.3 imports +- Skills: vercel-react-best-practices (required review for the changed dialogs) +- Read first: `apps/server/src/git/manager/guards.rs:152-257,305-320` (every emitted name); `apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.tsx:310-330,397-404`; `apps/web/src/components/gitManager/toolbar/GitManagerBranchDropdown.tsx:140-176`; `apps/web/src/components/gitManager/GitManagerToolbar.tsx:444-453` (the dirty checkout dialog) +- Tier: standard +- TDD: red-green +- Done when: `cd apps/web && node ../../scripts/run-local-vp.mjs test run --project unit src/components/gitManager/dialogs src/components/gitManager/toolbar` exits 0 + +Steps + +1. [ ] File the follow-up issue with `gh issue create --repo mubeda/BibCode`, titled "Git Manager: branch dialogs do not read the server's block reasons", stating the names on each side with file lines and placeholders only. Record its number in the task report; the pull request closes it. +2. [ ] Write failing tests with mixed guard arrays, so a test cannot pass on `blocked[0]`: the Delete dialog for a branch blocked with `[{ operation: "merge", ... }, { operation: "delete-branch", code: "default-branch", message: "Delete is blocked: this is the default branch." }]` shows the delete message and disables Delete; a branch blocked only for `merge` can still be deleted and renamed; the Rename dialog shows the `rename-branch` reason and not an unrelated one; in the dropdown, a branch blocked for `checkout` with code `dirty-working-tree` still opens the Stash or Bring dialog, a `merge` or `rebase` dirty reason does not stop checkout, a worktree-held branch still redirects, and a real checkout block shows its reason. +3. [ ] Run the Done when command. Expected: FAIL, on the missing delete message and on the checkout cases that pick an unrelated reason. +4. [ ] Create `gitManagerGuardOperations.ts` with the three constants and use them in the dialog lookups and the dropdown predicate, selecting each action's own reason. The server and the request tags are not changed (plan decision P2). +5. [ ] Run the Done when command. Expected: PASS. +6. [ ] Prove the tests can fail: set `GUARD_DELETE_BRANCH` to `"branch-delete"`, run the Done when command. Expected: FAIL. Restore and run again. Expected: PASS. + +### Task 2.2: Make the server the authority for a remote branch delete + +- Satisfies: R7 +- Depends on: none +- Files: modify `apps/server/src/git/manager/refs.rs`; modify `apps/server/src/git/manager/operations.rs`; modify `apps/server/src/git/repository.rs`; modify `docs/reference/mcp.md` +- Interfaces: consumes the existing ref listing and `git symbolic-ref refs/remotes//HEAD`; produces `GitManagerRefEntry.isDefault === true` on the remote entry that its remote's `HEAD` points to, with no contract change, which Task 2.3 reads +- Skills: rust-best-practices (ref reader change stays idiomatic and Clippy clean) +- Read first: `apps/server/src/git/manager/refs.rs:270-370,405-425,720-790` (the reader, the name parsing, and the existing symbolic-HEAD test); `apps/server/src/git/repository.rs:6229-6267` (how the one local default is derived) +- Tier: most capable +- TDD: red-green +- Done when: `cargo test -p bibcode-server refs`, `cargo test -p bibcode-server operations` and `cargo test -p bibcode-server repository`, each run on its own, exit 0 with the new tests + +Rules for this task + +The remote delete push has three callers: the `remote-branch-delete` operation (the new UI and the MCP tool `git_delete_remote_branch`), and local `branch-delete` with `deleteRemote` (`operations.rs:1565-1621`). The rules below apply to all three, through one shared helper, each with a failing test first in a temporary repository with a bare remote: + +- The push names the destination explicitly, `:refs/heads/`, in `git_manager_delete_remote_branch` (`repository.rs:4560-4575`). Test: the branch is already gone and a same-named tag exists; the tag survives and the operation fails with the Git error. +- Before the push, one `git ls-remote --symref HEAD refs/heads/` through the same network runner and sign-in path gives the remote's default branch and the branch's current commit. Refuse, deleting nothing, when: the branch is the remote's default ("Delete is blocked: this is the remote's default branch."); the default cannot be read ("The remote's default branch could not be checked."); or a local tracking ref `refs/remotes//` exists and points to a different commit than the remote branch ("This branch changed on the remote since the last fetch. Fetch, then delete it."). The last rule also covers a remote whose fetch mapping makes the tracking name point at another branch. A branch with no local tracking ref (an MCP caller naming a branch never fetched) is not compared. +- The check runs again when a request is resumed after sign-in. +- `remote-branch-delete` stays allowed during an in-progress merge, rebase, cherry-pick, revert and squash: one test over the five states (spec D5). +- Local `branch-delete` with `deleteRemote` whose upstream is the remote's default is refused before the local branch is deleted. Test it. +- Add the new refusals to the `git_delete_remote_branch` entry of `docs/reference/mcp.md`. +- File two follow-up issues with `gh issue create` (placeholders only) for the defects this task fixes that were there before: the unqualified push destination can delete a tag, and a local delete can remove a remote's default branch. Record the numbers in the task report. + +Steps + +1. [ ] Write the failing tests the Rules above list, and failing tests in `refs.rs`, in temporary repositories built the way the existing test at `:723` builds one: with remotes `origin` (HEAD to `origin/main`) and `upstream` (HEAD to `upstream/trunk`), `origin/main` and `upstream/trunk` have `is_default` true and `upstream/main`, `origin/feature` false; a remote with no `HEAD` ref marks none of its branches; the `/HEAD` rows stay excluded; the local `is_default` is unchanged. +2. [ ] Run `cargo test -p bibcode-server refs`, then `cargo test -p bibcode-server operations`, then `cargo test -p bibcode-server repository`. Expected: FAIL, on the two remote defaults and on each new refusal. +3. [ ] Implement the shared helper and the explicit destination of the Rules above. Then, while reading refs, keep each `refs/remotes//HEAD` symbolic target and set `is_default` on the remote entry whose full ref equals it. Use the data the ref listing already returns when it carries the symbolic target; add at most one extra Git call per snapshot otherwise, through the same cancellable repository runner. Log a failure to read a symbolic target with `tracing::warn!` and treat that remote's default as unknown. +4. [ ] Run the three `cargo test` commands of step 2, one at a time. Expected: PASS. +5. [ ] Prove the tests can fail: skip the assignment for remote entries, run the command. Expected: FAIL. Restore and run again. Expected: PASS. +6. [ ] Run `cargo fmt --all --check` and `cargo clippy -p bibcode-server --all-targets -- -D warnings`. Expected: no errors. If the snapshot's wire shape changed in any way, run `vp run check:contracts` and report it to the executor, since phase 3 owns the fixtures. + +### Task 2.3: Delete a remote branch from the branch list + +- Satisfies: R6, R7, R8 +- Depends on: 2.1, 2.2 +- Files: create `apps/web/src/components/gitManager/toolbar/remoteBranchRef.ts`; create `apps/web/src/components/gitManager/toolbar/remoteBranchRef.test.ts`; modify `apps/web/src/components/gitManager/toolbar/GitManagerBranchDropdown.tsx`; test `apps/web/src/components/gitManager/toolbar/GitManagerBranchDropdown.test.tsx`; modify `apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.tsx`; test `apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.test.tsx`; modify `apps/web/src/components/gitManager/GitManagerToolbar.tsx`; test `apps/web/src/components/gitManager/GitManagerToolbar.test.tsx`; modify `apps/web/src/components/gitManager/GitManagerPanel.tsx` +- Interfaces: consumes the `remote-branch-delete` request (`_tag`, `cwd`, `projectId`, `remote`, `branch`, optional `expectedDestination`; read the exact shape at `packages/contracts/src/gitManager.ts:251-259`), `GitManagerRefsSnapshot.remotes` and `.defaultBranch`, `GitManagerRefEntry.isDefault` from Task 2.2, the guard constants from Task 2.1, and `useGitSignInFlow` (`apps/web/src/components/gitSignIn/useGitSignInFlow.ts`). Produces `splitRemoteBranchRef(name: string, remotes: ReadonlyArray): { remote: string; branch: string } | "ambiguous" | null` and `remoteDeleteBlockedReason(ref: GitManagerRefEntry, split: ReturnType, snapshot: Pick): string | null` +- Skills: vercel-react-best-practices (required review for the changed components); better-ui (destructive confirm copy and disabled-state reasons) +- Read first: `apps/web/src/components/gitManager/toolbar/GitManagerBranchDropdown.tsx:228-253`; `apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.tsx:385-458`; `apps/web/src/components/gitManager/GitManagerToolbar.tsx:338-371,461-465,512-520`; `apps/web/src/components/gitManager/GitManagerPanel.tsx:498-523,1048-1054` (the sign-in offer and its resume); `apps/web/src/state/gitManager.ts:35-52` +- Tier: most capable +- TDD: red-green +- Done when: `cd apps/web && node ../../scripts/run-local-vp.mjs test run --project unit src/components/gitManager src/components/gitSignIn` exits 0 + +Rules for this task + +- The client's checks give an early, visible reason; the server of Task 2.2 decides. A server refusal is shown in the dialog like any Git error. +- Use the real event shape in tests: a rejection arrives as `output` events on stderr followed by a `failed` summary, and the dialog shows the stderr text. After an accepted sign-in, the resumed request's success must reach the dialog that owns the request, which then closes and refreshes; `GitManagerPanel.tsx:505-523` discards that result today, so the shared hook returns it. A declined sign-in leaves the dialog open. +- A symbolic `HEAD` row never reaches the client (`refs.rs` drops it): assert that in a test and give the helper no `HEAD` case. +- File a follow-up issue for the defect this task fixes that was there before: the toolbar's branch delete never offers sign-in. Record its number in the task report. + +Steps + +1. [ ] Write failing tests in `remoteBranchRef.test.ts`. `splitRemoteBranchRef("origin/feature/a", ["origin"])` gives `{ remote: "origin", branch: "feature/a" }`; a name no remote prefixes gives `null`; with remotes `["team", "team/fork"]`, `"team/fork/x"` gives `"ambiguous"`, because two remotes prefix it; with `["origin", "origin-fork"]`, `"origin-fork/x"` gives remote `origin-fork`, because `origin/` does not prefix it. `remoteDeleteBlockedReason` returns "Delete is blocked: this is the remote's default branch." when `ref.isDefault` is true; "Delete is blocked: two remotes match this name. Delete it from a terminal." for `"ambiguous"`; "Delete is blocked: the remote of this branch is unknown." for `null`; and `null` otherwise, including when the remote's default is unknown: the server checks it before deleting (Task 2.2), and the dialog says so. +2. [ ] Write failing component tests. A remote row renders Delete and no Rename; a blocked row's button is disabled, its reason is visible in the row's description and exposed as the accessible description, and activating it sends nothing. Choosing Delete opens a dialog titled "Delete Remote Branch?" that names the remote and the branch, says the local branch is kept and that the remote may refuse a protected branch, and requires the confirmation checkbox. Confirming sends exactly one request with `_tag: "remote-branch-delete"`, the snapshot's `cwd` and `projectId`, and that `remote` and `branch`; if the row is gone from a newer snapshot when Confirm is pressed, nothing is sent and the dialog says the branch no longer exists. A failed event that carries a sign-in offer shows the existing sign-in prompt, and accepting it sends the offer's `resume` request unchanged, `expectedDestination` included; declining leaves the dialog open with the failure. A protected-branch rejection shows the Git error text in the dialog, which stays open. After success the dialog closes and, with a refreshed snapshot that lacks the row, the row is gone, both when a local branch of the same name exists (still listed) and for a remote-only branch. The existing local delete with "Also delete the branch from its remote" still sends `branch-delete` with `deleteRemote`, and now also reaches the sign-in prompt. +3. [ ] Run the Done when command. Expected: FAIL, on the missing module, the missing Delete button and the missing sign-in handling. +4. [ ] Implement `remoteBranchRef.ts`; the remote row's Delete button; a `delete-remote` dialog kind that reuses the local dialog's layout and `GitManagerDisabledReasonButton`; and the toolbar submission. Move the panel's sign-in wrapper (`GitManagerPanel.tsx:498-523`) into a hook in `apps/web/src/components/gitManager/` that both the panel and the toolbar's runner use, so there is one implementation of offer and resume; do not copy it. +5. [ ] Run the Done when command. Expected: PASS. +6. [ ] Prove the tests can fail: make `remoteDeleteBlockedReason` return `null` always, run the Done when command. Expected: FAIL in the default-branch and ambiguity tests. Restore and run again. Expected: PASS. +7. [ ] Review the changed components against `vercel-react-best-practices` and the dialog and disabled states against `UI.md`; record both in the task report, with the user-visible text for the phase 4 update of `docs/user/workspace-ui.md`. +8. [ ] Run `vp check`. Expected: no errors in the files this phase owns. diff --git a/docs/plans/2026-11-20-undo-remote-delete-antigravity/phases/PHASE-03-antigravity-terminal.md b/docs/plans/2026-11-20-undo-remote-delete-antigravity/phases/PHASE-03-antigravity-terminal.md new file mode 100644 index 000000000..3a3f777af --- /dev/null +++ b/docs/plans/2026-11-20-undo-remote-delete-antigravity/phases/PHASE-03-antigravity-terminal.md @@ -0,0 +1,128 @@ +# Phase 3: Antigravity terminal + +- Goal: An Antigravity provider instance can be enabled in Settings and offers an Antigravity Terminal that starts `agy`; it never offers or starts a chat; tests and the provider guide are in place. +- Round: 1 +- Depends on: none +- Owns: `docs/plans/2026-11-20-antigravity-terminal-design.md`, `packages/contracts/src/settings.ts`, `packages/contracts/src/model.ts`, `packages/contracts/fixtures/**`, `apps/server/src/server_settings/**`, `apps/server/src/production/provider_inventory.rs`, `apps/server/src/production/control.rs`, `apps/server/src/production/provider_runtime.rs`, `apps/server/src/hermetic_guard.rs`, `apps/server/tests/support/hermetic_providers.rs`, `apps/server/src/test_support/mod.rs`, `apps/web/src/components/chat/provider*.ts`, `apps/web/src/components/chat/ChatHeaderPanelMenu.logic.ts`, `apps/web/src/components/settings/**`, `apps/web/src/session-logic.ts`, `apps/web/src/providerInstances.ts`, `apps/web/src/providerModels.ts`, `apps/web/src/threadProviderBinding.ts`, `apps/web/visual/typography/**`, `docs/providers/**`, `docs/architecture/providers.md`, `docs/README.md` +- Must not touch: `packages/contracts/src/editor.ts`, `apps/server/src/production/editor_launch.rs`, `apps/web/src/components/files/**`, `apps/web/src/components/gitManager/**`, `apps/server/src/git/**`, `apps/desktop/**`, `docs/user/workspace-ui.md` (phase 4 updates it) +- Skills: tdd (failing test first for every registration and launch rule) +- Read first: issue #399 (the request and acceptance criteria); `research-antigravity.md` in this plan folder (the CLI, ACP, SDK and terms facts, with what is unconfirmed); `reviews/plan-review-1.md` findings 3, 8, 9 and 10; `docs/providers/cursor.md` (a terminal without an observer); `docs/architecture/providers.md` +- Checkpoint: the Done when commands of Tasks 3.2 to 3.4 exit 0; in Settings > Agents an Antigravity card exists, disabled by default, and with it enabled the AI Terminal menu lists Antigravity Terminal and no Antigravity chat. + +Phase rules: + +- Chat exclusion is one shared rule applied where a chat is chosen. No file outside this phase's ownership is edited for it; `FileBrowserPanel.tsx` (phase 1's folder) and `useAddProjectWorkflow.ts` get the rule through `resolveDefaultAgentInstanceId`. +- Each `cargo test` invocation takes one filter. Every `cargo` command runs under the executor's shared build lock. +- `ProviderDriverKind` is an open branded string (`packages/contracts/src/providerInstance.ts:16-32`), so no closed union gains a member. + +## Tasks + +### Task 3.1: Write and review the Antigravity terminal design note + +- Satisfies: R10 +- Depends on: none +- Files: create `docs/plans/2026-11-20-antigravity-terminal-design.md` +- Interfaces: consumes `research-antigravity.md`; produces the classified registration table, the chat-eligibility rule and the model and effort rule that Tasks 3.2 to 3.5 implement +- Skills: mstack-research (re-check any flag the research marks unconfirmed) +- Read first: `apps/web/src/components/chat/providerTerminalActions.ts:33-236`; `apps/web/src/components/chat/providerAgentActions.ts`; `apps/web/src/components/chat/ChatHeaderPanelMenu.logic.ts`; `apps/web/src/providerModels.ts:92-105`; `apps/server/src/production/provider_inventory.rs:181-191,215-314,2012-2064`; `apps/server/src/production/provider_runtime.rs:2468-2473,2532-2543,6730-6737,6975-6985`; `apps/server/src/production/control.rs:2817-2841,2976-3013`; `packages/contracts/src/settings.ts:425-470,571-578,650-670,762-830`; `packages/shared/src/providerSessionDefaults.ts:89-137,242-254,303-337`; an existing note, `docs/plans/2026-11-18-server-commands-design.md` (the shape) +- Tier: most capable +- TDD: exempt (a design document with no behavior to test) +- Done when: `test -s docs/plans/2026-11-20-antigravity-terminal-design.md` exits 0, `vp check` exits 0, and the note's "Review record" section lists a Codex review and an advisor review with every finding handled; observable in the note + +Steps + +1. [ ] Confirm from https://antigravity.google/docs/cli/reference/ the spelling of `--model`, `--effort` and `--dangerously-skip-permissions`, and that plain `agy` starts the TUI. That page does not list `--version`: cite Google's getting-started page for `agy --version`, or record it as unverified in the note. A flag that differs changes spec R12 only through a Ruling logged in `progress.md`. +2. [ ] Run `rg -n '"cursor"|cursor-agent|CursorSettings|CURSOR_DRIVER_KIND|make\("cursor"\)|"grok"' packages apps/web/src apps/web/visual apps/server/src apps/server/tests -g '!**/provider/cursor/**' -g '!**/provider/grok/**'`. Expected: a list of sites; classify each in a table as "needs an antigravity entry", "chat only, must not get one" or "unrelated". The table must include the sites review finding 8 names. +3. [ ] Decide and write, each with the alternative that lost and its trade-off: driver slug `antigravity`; default disabled (spec D7); the Settings card (binary path, the existing icon, a line that chat is not supported yet, and whether a model and effort default can be set there); the permission flag (spec D8); model and effort: argv takes `--model` and `--effort` only from the raw `settings.providerSessionDefaults.antigravity` value (`model`, and the effort option in `options`), never from the resolver's fallback, because the driver has no catalog and the fallback model belongs to another vendor; chat eligibility: one exported predicate used by `buildProviderAgentActions`, `resolveDefaultAgentInstanceId`, `resolveSelectableProvider` and any other chooser the table finds; the server refusal placed before `canonical_provider_kind` with its own error text; the display name on the Rust label path; first-run prompts of the TUI appearing in the embedded terminal; the PATH clash with an IDE launcher; and Google's stated position on third-party hosts for consumer plans, with what the terminal does (it runs the user's own unmodified CLI interactively). +4. [ ] Get a Codex read-only review of the note (the `codex` skill, `gpt-6.2-sol` at `high`) and an advisor review (the executing session's advisor tool, called with no arguments after the note is saved; a host without it runs a second fresh-context, read-only review on the most capable model and logs it as such). Process both with `mstack-receive-review`, fix accepted findings, and append a "Review record" section with each finding and its outcome. By spec D6 this is the note's approval. +5. [ ] Run `vp check`. Expected: exit 0. + +### Task 3.2: Register the antigravity driver in settings, inventory and the hermetic lists + +- Satisfies: R11, R14 +- Depends on: 3.1 +- Files: modify `packages/contracts/src/settings.ts`; modify `packages/contracts/src/model.ts`; modify `packages/contracts/fixtures/**` (regenerated); modify `apps/server/src/server_settings/mod.rs`; modify `apps/server/src/production/control.rs`; modify `apps/server/src/production/provider_inventory.rs`; modify `apps/server/src/production/provider_runtime.rs` (the label only); modify `apps/server/src/hermetic_guard.rs`; modify `apps/server/tests/support/hermetic_providers.rs`; modify `apps/server/src/test_support/mod.rs` +- Interfaces: consumes the design note's table; produces the contract `AntigravitySettings` (`enabled`, default `false`; `binaryPath`, default `"agy"`; `customModels`), the `providers.antigravity` key with its patch schema, and a `ServerProvider` snapshot with `driver: "antigravity"` and `displayName: "Antigravity"`, which Tasks 3.3 and 3.4 use +- Skills: rust-best-practices (settings and inventory changes stay idiomatic) +- Read first: `docs/plans/2026-11-20-antigravity-terminal-design.md` (binding); `apps/server/src/server_settings/mod.rs:10-80,330-340,636-700`; `apps/server/src/production/provider_inventory.rs:2915-2925` (the exact-order inventory assertion); `.repos/effect-smol/LLMS.md` (before editing Schema code) +- Tier: most capable +- TDD: red-green +- Done when: each of `cargo test -p bibcode-server server_settings`, `cargo test -p bibcode-server provider_inventory`, `cargo test -p bibcode-server hermetic` and `cargo test -p bibcode-server control` exits 0 with the new tests, and `vp run check:contracts` exits 0 after the regenerated fixtures are staged + +Steps + +1. [ ] Write failing Rust tests: `BUILTIN_DEFAULTS` gains `("antigravity", false, "agy")`; a settings file with no `antigravity` key decodes and yields a disabled instance; a partial object `{ "binaryPath": "custom-agy" }` keeps `enabled` false; an explicit `enabled: true` persists through a settings patch, and `validate_legacy_provider_settings` accepts `providers.antigravity` with `binaryPath` and rejects a non-string one; `default_provider_binary("antigravity")` is `"agy"`; `is_builtin_driver("antigravity")` is true; the synthesized roster and the exact-order assertion include it; a disabled instance is not probed, an enabled one is probed with the configured binary and the single argument `--version` through the existing fixture mechanism (success; a binary that cannot be started reported as not installed; a binary whose `--version` exits non-zero reported as installed with a warning, which is the existing inventory behavior at `provider_inventory.rs:731-742`; both failure cases use an inert fixture executable); the snapshot's `displayName` is "Antigravity"; `GUARDED_PROGRAMS` contains `"agy"`; `BUILTIN_PROVIDER_DRIVERS` and the hermetic enabled table include `antigravity`, so the existing parity test passes. +2. [ ] Run the four `cargo test` commands of Done when, one at a time. Expected: FAIL on each new assertion. +3. [ ] Implement, following the design note's table: `AntigravitySettings` and its patch in `settings.ts` next to `CursorSettings`; the label in `model.ts` and in the Rust label function; the defaults, the patch validation and the roster; the `agy` case in `default_provider_binary`; `"agy"` in `GUARDED_PROGRAMS`; the hermetic lists. +4. [ ] Run the four `cargo test` commands. Expected: PASS. +5. [ ] Regenerate and check the contract fixtures: run `vp run check:contracts`. Expected: it rewrites `packages/contracts/fixtures` and then fails its final `git diff --exit-code` if a fixture changed; review that diff, stage it with `git add packages/contracts/fixtures`, and run the command again. Expected: exit 0. +6. [ ] Prove a test can fail: return the driver slug from `default_provider_binary` for `antigravity`, run `cargo test -p bibcode-server provider_inventory`. Expected: FAIL. Restore and run again. Expected: PASS. +7. [ ] Run `cargo fmt --all --check` and `cargo clippy -p bibcode-server --all-targets -- -D warnings`. Expected: no errors. + +### Task 3.3: Refuse a chat start for an Antigravity instance on the server + +- Satisfies: R13 +- Depends on: 3.2 +- Files: modify `apps/server/src/production/provider_runtime.rs` +- Interfaces: consumes the instance-to-driver resolution at `provider_runtime.rs:6730-6737` and `canonical_provider_kind` (`:6975-6985`); produces a `ProviderRuntimeError` variant or message for a terminal-only driver, shown to the user as "Antigravity does not support chat yet. Open an Antigravity Terminal instead." +- Skills: rust-best-practices (error variant and boundary logging) +- Read first: `apps/server/src/production/provider_runtime.rs:2440-2545,6700-6760,6960-6990`; `docs/plans/2026-11-20-antigravity-terminal-design.md` +- Tier: standard +- TDD: red-green +- Done when: `cargo test -p bibcode-server provider_runtime` exits 0 with the new tests + +Steps + +1. [ ] Write failing tests: a chat start that names an Antigravity instance by its default id, and one that names a custom instance id whose driver is `antigravity`, both fail with the message above, before any process is spawned (assert through the hermetic fixture that no program ran); a start for an unknown driver still gives the existing "turned off or not set up" message. +2. [ ] Run `cargo test -p bibcode-server provider_runtime`. Expected: FAIL, because both starts give the generic message. +3. [ ] Implement the refusal before `canonical_provider_kind` is called, with `tracing::warn!` at that boundary and no prompt or message content in the log. +4. [ ] Run `cargo test -p bibcode-server provider_runtime`. Expected: PASS. +5. [ ] Prove the test can fail: remove the early refusal, run the command. Expected: FAIL. Restore and run again. Expected: PASS. +6. [ ] Run `cargo fmt --all --check` and `cargo clippy -p bibcode-server --all-targets -- -D warnings`. Expected: no errors. + +### Task 3.4: Offer Antigravity Terminal and never an Antigravity chat in the client + +- Satisfies: R11, R12, R13 +- Depends on: 3.2 +- Files: modify `apps/web/src/components/chat/providerTerminalActions.ts`; test `apps/web/src/components/chat/providerTerminalActions.test.ts`; modify `apps/web/src/components/chat/providerAgentActions.ts`; test `apps/web/src/components/chat/providerAgentActions.test.ts`; modify `apps/web/src/providerModels.ts` and its test; modify `apps/web/src/threadProviderBinding.ts`; test `apps/web/src/threadProviderBinding.test.ts`; modify `apps/web/src/components/settings/providerDriverMeta.ts`; modify `apps/web/src/components/settings/SettingsPanels.tsx` and `ProviderInstanceCard.tsx` where the card or the defaults control needs the terminal-only case; test `apps/web/src/components/settings/SettingsPanels.test.tsx`; modify `apps/web/src/components/chat/providerIconUtils.ts`; modify `apps/web/src/session-logic.ts`; modify `apps/web/visual/typography/settings.tsx` and its tests if the new Settings entry changes them +- Interfaces: consumes the `"antigravity"` driver kind and `AntigravitySettings` from Task 3.2, `ProviderSessionDefault` (`model`, optional `options`; `packages/contracts/src/settings.ts:571-578`), and `AntigravityIcon` (`apps/web/src/components/Icons.tsx:641-646`); produces `isChatCapableDriver(driver: ProviderDriverKind): boolean` exported from `apps/web/src/providerInstances.ts` +- Skills: vercel-react-best-practices (required review for the changed components); better-ui (the terminal-only Settings card explains itself) +- Read first: `docs/plans/2026-11-20-antigravity-terminal-design.md` (binding); `apps/web/src/components/chat/providerTerminalActions.ts:119-236`; `apps/web/src/components/chat/providerAgentActions.ts:40-114`; `apps/web/src/providerModels.ts:92-105`; `apps/web/src/components/settings/SettingsPanels.tsx:2077-2117`; `apps/web/src/components/settings/ProviderInstanceCard.tsx:771-779` +- Tier: most capable +- TDD: red-green +- Done when: `cd apps/web && node ../../scripts/run-local-vp.mjs test run --project unit src/components/chat src/components/settings src/providerModels.test.ts src/threadProviderBinding.test.ts` exits 0 + +Rules for this task + +- Chat eligibility lives in the two central selectors, `resolveSelectableProvider` (`apps/web/src/providerModels.ts`) and `resolveThreadProviderBinding` (`apps/web/src/threadProviderBinding.ts:108-139,237-245`), which `ChatView`, the Sidebar's default-thread creation and worktree adoption all go through, and in `buildProviderAgentActions` / `resolveDefaultAgentInstanceId`. Add tests in `threadProviderBinding.test.ts` that an enabled Antigravity instance listed first, or alone, never becomes the implicit chat target of a fresh thread, a default thread or an adopted worktree, and that an explicit terminal selection is kept. A caller that bypasses the selectors is named in the task report and handed to the executor, not edited. +- Add one production-shaped test: an inventory snapshot with an enabled, installed Antigravity instance goes through the real menu builder, the terminal action is clicked, and the terminal-open request carries the thread's checkout as working directory, the command and the activity. +- The typography gallery is not in the `unit` project. If a typography fixture changes, run `cd apps/web && node ../../scripts/run-local-vp.mjs test run --config visual/typography/vite.config.mjs` (from `docs/testing/typography-fixtures.md`). Expected: PASS. + +Steps + +1. [ ] Write failing launch tests for an enabled Antigravity entry: executable `agy`; args exactly `["--dangerously-skip-permissions"]` when `providerSessionDefaults` has no `antigravity` key, even though the resolver would supply a fallback model; `["--dangerously-skip-permissions", "--model", "m1"]` with a raw default of model `m1` alone; with model `m1` and effort `high`, the same plus `"--effort", "high"`; `activity` equals `{ driverKind: "antigravity", providerInstanceId: }`; an instance `binaryPath` of `custom-agy` replaces the executable; no arg is `--continue`, `-c` or `--conversation`; the label is "Antigravity Terminal"; a model value long enough to exceed the command bounds yields the disabled action with the existing bounds reason. +2. [ ] Write failing chat-eligibility tests: `buildProviderAgentActions` returns a terminal action and no chat action for an Antigravity entry; `resolveEffectiveProviderAgentAction` with a saved chat selection naming it falls back to another ready chat, and a saved terminal selection naming it is kept; `resolveDefaultAgentInstanceId` never returns the Antigravity instance for a chat default, including when it is the only instance (it returns the built-in default instance id instead); `resolveSelectableProvider` skips an enabled Antigravity entry when it falls back. Add a Settings test that the Antigravity card renders with the binary path placeholder `agy`, the line that chat is not supported yet, and no control that leads to a chat. +3. [ ] Run the Done when command. Expected: FAIL, on the missing launch definition and the present chat action. +4. [ ] Implement: `isChatCapableDriver`; the `antigravity` entry in `DEFINITIONS` and argv built from the raw settings value as the design note rules; the predicate in the four choosers; the Settings definition with `AntigravityIcon`, the icon map entry, and the card text. +5. [ ] Run the Done when command. Expected: PASS. +6. [ ] Prove a test can fail: make `isChatCapableDriver` return true always, run the Done when command. Expected: FAIL in the chat-eligibility tests. Restore and run again. Expected: PASS. +7. [ ] Run `vp run typecheck`. Expected: no type errors. If a typography fixture changed, review `docs/testing/typography-fixtures.md` and say so in the task report. +8. [ ] Review the changed components against `vercel-react-best-practices` and the Settings card and menu against `UI.md`; record both in the task report, with the user-visible text for the phase 4 update of `docs/user/workspace-ui.md`. + +### Task 3.5: Document the Antigravity terminal + +- Satisfies: R14 +- Depends on: 3.3, 3.4 +- Files: create `docs/providers/antigravity.md`; modify `docs/providers/README.md`; modify `docs/architecture/providers.md`; modify `docs/README.md` +- Interfaces: consumes the shipped behavior of Tasks 3.2 to 3.4; produces nothing another task uses +- Skills: better-writing (plain provider guide wording) +- Read first: `docs/providers/cursor.md` (the guide shape and how `--yolo` is documented); `docs/plans/2026-11-20-antigravity-terminal-design.md`; `research-antigravity.md` in this plan folder +- Tier: cheap +- TDD: exempt (documentation with no behavior to test) +- Done when: `vp run check:markdown-links` exits 0 and `vp check` exits 0 + +Steps + +1. [ ] Write `docs/providers/antigravity.md`: what is supported (AI Terminal only; chat is not yet), install check `agy --version`, sign-in (`agy` interactively, or `agy acp --login` on a machine without a browser), the first-run prompts the TUI shows in the terminal, the launch command and what `--dangerously-skip-permissions` means, the binary path setting, how a model and effort default reaches the command, status reported as unavailable, the PATH clash between the `agy` CLI and an IDE launcher of the same name with how to check which one is found, and Google's stated position on third-party hosts for consumer plans with a link to its terms. Versions and command names only; no account, host or local path. Expected: the guide exists with each of those sections. +2. [ ] Add the guide to `docs/providers/README.md` and to `docs/README.md` under Provider guides, and add the terminal-only mode and the disabled default to `docs/architecture/providers.md`. +3. [ ] Run `vp run check:markdown-links` and `vp check`. Expected: exit 0 for both. diff --git a/docs/plans/2026-11-20-undo-remote-delete-antigravity/phases/PHASE-04-integration.md b/docs/plans/2026-11-20-undo-remote-delete-antigravity/phases/PHASE-04-integration.md new file mode 100644 index 000000000..27ca26df2 --- /dev/null +++ b/docs/plans/2026-11-20-undo-remote-delete-antigravity/phases/PHASE-04-integration.md @@ -0,0 +1,63 @@ +# Phase 4: Integration and pull request + +- Goal: The four feature phases are integrated on one branch, reviewed, every follow-up is ticketed and fixed, the final commit passes every gate, and one pull request is open. +- Round: 2 +- Depends on: 1, 2, 3, 5 +- Owns: `docs/plans/2026-11-20-undo-remote-delete-antigravity/progress.md`, `docs/plans/README.md`, `docs/user/workspace-ui.md`, `docs/testing/**`, any file a follow-up fix needs +- Must not touch: `.repos/**`, `.codegraph/**` +- Skills: issue-delivery (acceptance checklist and a checkpoint before costly runs) +- Read first: `AGENTS.md` › Task Completion Requirements; `docs/testing/README.md`; `docs/operations/ci.md`; `scripts/check-agent-delivery.mjs` (what the checkpoint must hold) +- Checkpoint: every command in `plan.md` › End-to-end verification exits 0 on the commit that is pushed, and the pull request lists issues #397, #398, #399, #400 and every follow-up issue as closed by it. + +## Tasks + +### Task 4.1: Integrate, review and fix follow-ups + +- Satisfies: R15 +- Depends on: 1.2, 1.3, 2.3, 3.5, 5.1 +- Files: modify `docs/user/workspace-ui.md`; modify `docs/plans/README.md`; modify the testing runbooks under `docs/testing/` that the change affects; modify any file a follow-up fix needs +- Interfaces: consumes the three phase branches and their task reports; produces one candidate commit on the plan's branch +- Skills: mstack-receive-review (processes the Codex and advisor reviews); better-writing (the user guide text) +- Read first: the task reports of phases 1, 2, 3 and 5 (Rulings, "not run" items, the user-visible text for the guide); `docs/user/workspace-ui.md:1224-1243` (remote rows are described as checkout only today) and its AI Terminal notes +- Tier: standard +- TDD: red-green +- Done when: `git status --short` is empty on the plan's branch, `gh issue list --repo mubeda/BibCode --state open --json number,title` shows every follow-up issue with a fix commit named in `progress.md`, and both reviews are logged with every finding handled + +Rules for this task + +- One sequence for inline and workflow execution: integrate (a no-op inline), review, fix, commit the candidate. The final Codex and advisor reviews happen here, before the gates of Task 4.2, never after them. +- `docs/user/workspace-ui.md`'s AI Terminal notes link to `docs/providers/antigravity.md` (spec R14); `vp run check:markdown-links` proves the link. Expected: exit 0. + +Steps + +1. [ ] Integrate the phase branches into the plan's branch, in the order 5, 2, 3, 1. Run `git status --short`. Expected: clean, no conflict markers. +2. [ ] Update `docs/user/workspace-ui.md`: remote branch rows offer Delete with the default-branch rule, and the AI Terminal notes list Antigravity as a terminal whose status is unavailable, and View PR is described as opening the PR panel. Review the testing runbooks the change affects (the packaged UI suite gained a spec; provider visibility gained a driver; typography fixtures if they changed) and update them, or record that they were reviewed and remain accurate. Add this plan folder to `docs/plans/README.md`. +3. [ ] Get a Codex read-only review of `git diff origin/main...HEAD` against `spec.md`, and an advisor review. Process both with `mstack-receive-review`. +4. [ ] For every accepted finding and every follow-up (a Ruling, a deferred finding, a "not run" that is real work, a failure seen outside the changed areas): file a GitHub issue with `gh issue create` (placeholders only), write the test that fails, run it. Expected: FAIL. Fix it, run it again. Expected: PASS. Log the issue number with its fix commit in `progress.md`. +5. [ ] Review `git diff origin/main...HEAD` for unintended edits, debug output, leftover logging from Task 1.1, and sensitive data. Expected: none. Commit; this commit is the candidate. + +### Task 4.2: Gate the candidate commit and open the pull request + +- Satisfies: R15 +- Depends on: 4.1 +- Files: modify `docs/plans/2026-11-20-undo-remote-delete-antigravity/progress.md` +- Interfaces: consumes the candidate commit of Task 4.1; produces the pull request +- Skills: bibcode-profiler (reads the Profiler data of the packaged run) +- Read first: `docs/testing/macos-desktop.md`; `docs/skills/bibcode-profiler/SKILL.md`; `docs/skills/issue-delivery/SKILL.md` +- Tier: standard +- TDD: exempt (verification and publication; it runs commands and adds no behavior) +- Done when: `gh pr view --repo mubeda/BibCode --json state,headRefOid,closingIssuesReferences` shows an open pull request whose head is the gated commit and which closes #397, #398, #399, #400 and every follow-up issue, and the six End-to-end verification results are logged in `progress.md` with that commit's SHA + +Rules for this task + +- Gate evidence does not move the gated commit: the results and the gated SHA go into the pull request body. The commit that closes this task in `progress.md` touches only that file, is made after the gates, and is not gated again. Any other change after the gates restarts this task from step 1. + +Steps + +1. [ ] Run `git rev-parse HEAD` and log the SHA as the gated commit. Expected: the candidate of Task 4.1. +2. [ ] Run `vp check`, `vp run typecheck`, `cargo fmt --all --check` and `cargo clippy -p bibcode-server -p bibcode-desktop --all-targets -- -D warnings`. Expected: exit 0 for each. +3. [ ] Run `vp run -r --concurrency-limit 1 test`. Expected: exit 0. +4. [ ] Write the issue-delivery checkpoint outside the repository, with `source` and `proof.source` set to the gated SHA and `proof.scope` `complete-caller`, and run `node scripts/check-agent-delivery.mjs `. Expected: exit 0. Then take the build lock, run `vp run test:ui:desktop:build`, and run `BIBCODE_E2E_PROFILER=1 vp run test:ui:desktop`. Expected: PASS, with `files-undo-shortcuts.e2e.ts` named in the run report. +5. [ ] Load `bibcode-profiler` and read that run's Profiler data. Expected: no new finding. +6. [ ] If any of steps 2 to 5 fails or finds something: go back to Task 4.1 step 4 for it, commit, and repeat this task from step 1 on the new commit. The gates are valid only for the SHA they ran on. +7. [ ] Run `git push -u origin HEAD` and open one pull request against `main` with `gh pr create`, whose body closes #397, #398, #399, #400 and the follow-up issues, lists each validation command with its result and the gated SHA, what was not run and why, the spec decisions that were the planning agent's calls (D1, D5, D7, D9, D12, plan decision P10, and D8, which the research first advised against), and the profiler coverage line (child processes: `agy` is spawned only by the terminal runtime; RPC methods: none added; removal paths: none; the chat refusal logs through `tracing::warn!`; on Task 1.2 branch B, the menu action reuses the existing event). Expected: the Done when command shows the pull request open on the gated commit. Publishing is authorized by the owner's request for this pull request; follow CI with cheap helpers, one run at a time. diff --git a/docs/plans/2026-11-20-undo-remote-delete-antigravity/phases/PHASE-05-view-pr-panel.md b/docs/plans/2026-11-20-undo-remote-delete-antigravity/phases/PHASE-05-view-pr-panel.md new file mode 100644 index 000000000..04eba0280 --- /dev/null +++ b/docs/plans/2026-11-20-undo-remote-delete-antigravity/phases/PHASE-05-view-pr-panel.md @@ -0,0 +1,40 @@ +# Phase 5: View PR opens the PR panel + +- Goal: The View PR / View MR button in Source Control opens BiBCode's own PR/MR panel, the menu keeps a browser entry, with tests. +- Round: 1 +- Depends on: none +- Owns: `apps/web/src/components/SourceControlPanel.tsx`, `apps/web/src/components/GitActionsControl.logic.ts`, `apps/web/src/components/SourceControlPrimaryAction.logic.ts`, and their tests +- Must not touch: `apps/web/src/components/gitManager/**`, `apps/web/src/components/gitSignIn/**`, `apps/web/src/components/files/**`, `apps/web/src/components/chat/**`, `apps/web/src/rightPanelStore.ts`, `apps/server/**` +- Skills: tdd (failing test first for the action kinds) +- Read first: issue #400 (the report and acceptance criteria); `UI.md` (a button does what its label says; safe defaults) +- Checkpoint: `cd apps/web && node ../../scripts/run-local-vp.mjs test run --project unit src/components/GitActionsControl.logic.test.ts src/components/SourceControlPrimaryAction.logic.test.ts src/components/SourceControlPanel.test.tsx` exits 0; in the app, View PR opens the PR panel and the browser stays closed. + +## Tasks + +### Task 5.1: Route View PR to the panel and keep a browser menu item + +- Satisfies: R16 +- Depends on: none +- Files: modify `apps/web/src/components/GitActionsControl.logic.ts`; test `apps/web/src/components/GitActionsControl.logic.test.ts`; modify `apps/web/src/components/SourceControlPrimaryAction.logic.ts` and its test; modify `apps/web/src/components/SourceControlPanel.tsx`; test `apps/web/src/components/SourceControlPanel.test.tsx` +- Interfaces: consumes the action kinds `open_pr` (browser, through `openPullRequestLink`) and `open_pr_panel` (through `useRightPanelStore.getState().openPullRequest(threadRef, { number, provider })`), and `canOpenInPanel` (`SourceControlPanel.tsx:431`, `GitActionsControl.logic.ts:100`); produces no new kind +- Skills: vercel-react-best-practices (required review for the changed components); better-ui (menu labels say where the PR opens) +- Read first: `apps/web/src/components/GitActionsControl.logic.ts:90-180,225-310`; `apps/web/src/components/SourceControlPrimaryAction.logic.ts:90-130` and every place it returns `open_pr`; `apps/web/src/components/SourceControlPanel.tsx:250-260,425-470,1018-1090`; `apps/web/src/components/pullRequests/pullRequestsAvailability.ts:41-52` and `PullRequestPanelSurface.tsx:61-66,91-103` (what the panel needs to show a pull request); `apps/web/src/components/chat/ChatHeaderActions.tsx:184-193` (the chat-header control's trigger is hidden) +- Tier: standard +- TDD: red-green +- Done when: `cd apps/web && node ../../scripts/run-local-vp.mjs test run --project unit src/components/GitActionsControl.logic.test.ts src/components/SourceControlPrimaryAction.logic.test.ts src/components/SourceControlPanel.test.tsx` exits 0 + +Rules for this task + +- "The panel can open" means it can show the pull request: combine the existing check (`canOpenPullRequestInPanel`, `SourceControlPanel.tsx:427-437`) with the server capability `pullRequestsReads` that the panel surface requires. On a server without that capability View PR opens the browser. A transient disconnect is not lack of support. +- Add `open_pr_panel` to both primary action types (`GitActionsControl.logic.ts:19-33`, `SourceControlPrimaryAction.logic.ts:28-37`), and give `resolveQuickAction` the panel flag as a parameter. +- Do not edit `GitActionsControl.tsx`: its trigger is hidden in production. If typecheck requires a change there, make the smallest compatibility change, name it in the task report, and tell the executor, because the file is outside this phase's ownership. +- Run the click tests for both action ladders (legacy and staging-area), for GitHub and GitLab wording, and for the browser fallback at component level. + +Steps + +1. [ ] Write failing tests. Logic: with an open PR and a panel that can show it (the combined flag of the Rules above), the quick action and the primary action labelled "View PR" have kind `open_pr_panel`, and the menu holds one panel-opening item "View PR" and one item "Open PR in browser" of kind `open_pr` (no item named "Open PR in panel"); with `canOpenInPanel` false, the quick and primary actions keep kind `open_pr` and the menu has the single browser item, as today; with GitLab terminology the labels say MR. Panel: clicking View PR calls `openPullRequest` with the PR's number and provider and does not call `openPullRequestLink`; choosing "Open PR in browser" calls `openPullRequestLink` with the PR URL. +2. [ ] Run the Done when command. Expected: FAIL, because View PR still has kind `open_pr`. +3. [ ] Implement: return `open_pr_panel` for the View actions when the panel can open, rename the menu items, handle `open_pr_panel` in `onPrimaryAction` and `onScPrimaryAction` of `SourceControlPanel.tsx`. Update the existing tests that pin "View PR" to `open_pr` only where the rule changed them. +4. [ ] Run the Done when command. Expected: PASS. +5. [ ] Prove the tests can fail: make the logic ignore `canOpenInPanel`, run the Done when command. Expected: FAIL. Restore and run again. Expected: PASS. +6. [ ] Run `vp check` and `vp run typecheck`. Expected: no errors. Review the change against `vercel-react-best-practices` and `UI.md`; record both in the task report, with the user-visible text for the phase 4 update of `docs/user/workspace-ui.md`. diff --git a/docs/plans/2026-11-20-undo-remote-delete-antigravity/plan.md b/docs/plans/2026-11-20-undo-remote-delete-antigravity/plan.md new file mode 100644 index 000000000..cc46d3f6d --- /dev/null +++ b/docs/plans/2026-11-20-undo-remote-delete-antigravity/plan.md @@ -0,0 +1,172 @@ +# Files undo shortcuts, remote branch delete, Antigravity terminal + +Status: Approved 2026-11-20 (owner's standing rule: reviewed by Codex and the advisor. Codex's last verdict was "Needs rework"; all its findings were applied and the round 2 fixes were not reviewed again) +Spec: spec.md (Status line: Approved 2026-11-20, sha256 9d9513bbe595) +Repository: this repository +Base: main + +## Goal + +1. Ctrl/Cmd+Z, Shift+Ctrl/Cmd+Z and Ctrl+Y move the Files editor history, in the source and rendered views and in the packaged desktop app (#398). +2. A remote branch row in Git Manager can be deleted after a confirmation, and server block reasons show in the branch dialogs (#397). +3. An enabled Antigravity instance offers an Antigravity Terminal that starts `agy`, and never offers a chat (#399). +4. View PR in Source Control opens the PR/MR panel, with a browser entry in the menu (#400). + +## Global constraints + +- One pull request against `main`; every follow-up found is ticketed and fixed in it (R15, D11). +- Antigravity executable default is `agy`, driver slug `antigravity`, permission flag `--dangerously-skip-permissions`, install probe `agy --version` (R11, R12, D8). +- `--continue` and `--conversation` are never passed on launch (R12). +- "Open in Antigravity" (`packages/contracts/src/editor.ts`, `apps/server/src/production/editor_launch.rs`) is not changed (R13). +- Ctrl+Y redoes on Windows and Linux only (D1). +- Remote delete sends the existing `remote-branch-delete` operation; no new server operation (R6). +- BiBCode never edits the user's Antigravity settings, hooks or MCP files and never reads Google credentials (research report, recommendations). +- Public repository: placeholders only, no real names, hosts, tokens or local paths (AGENTS.md, Sensitive Data). +- Privileged desktop operations cross `DesktopBridge` commands and events only (AGENTS.md, Architectural Decision Standards). +- No unit test may spawn a real provider CLI; `agy` joins the hermetic guard (R14). +- Each `cargo test` invocation takes one filter; `cargo` and packaged builds run one at a time under the executor's shared build lock. + +## Review focus + +1. The undo chord works in a browser but not in the packaged app, because the native Edit menu handles it differently on each platform. Pinned by Tasks 1.1 and 1.2. +2. A fix for Files undo breaks undo somewhere else (the inline comment textarea, the chat composer). Pinned by Tasks 1.2 and 1.3. +3. Remote Delete enabled on a remote's default branch, or resolved to the wrong remote when one remote's name prefixes another. Pinned by Tasks 2.2 and 2.3. +4. Antigravity chosen as a chat through a fallback path instead of the menu (saved default, first enabled provider, server routing). Pinned by Tasks 3.3 and 3.4. +5. A settings file written before this change fails to decode, or enables the driver. Pinned by Task 3.2. + +## Out of scope + +- Antigravity chat-panel driver over `agy acp`: a later issue (spec Non-goals). The research report records the transport, minimum version and risks for it. +- Terminal observer, resume flags, retargeting the editor command to `agy-ide` (spec Non-goals). +- Pull-request detection before a remote delete (D4). +- Deleting the local branch from the remote-delete dialog (D2). + +## Sources + +- Repository rules: `AGENTS.md` (pre-work, sensitive data, completion requirements, profiler coverage, runbook maintenance); `UI.md` (review of every user-visible change). +- Repository docs: `docs/README.md` (index); `docs/reference/scripts.md` (commands below); `docs/providers/README.md` and `docs/providers/cursor.md` (the terminal-without-observer precedent); `docs/architecture/providers.md` (driver ownership); `docs/user/keybindings.md` and `docs/user/workspace-ui.md` (user guides to update); `docs/testing/README.md` and the three desktop runbooks (packaged UI runs and labs); `docs/skills/issue-delivery/SKILL.md` (checkpoint before costly runs). +- External: issues #397, #398, #399, #400 (the requests, with their code references at 3b7407928). +- External: `research-antigravity.md` in this folder, a research report of 2026-11-20 on the Antigravity CLI, ACP mode, SDKs, terms and host signals, with source links and a list of what is unconfirmed. It holds for CLI 1.5.13. It decides: plain `agy` starts the TUI; no SDK fits; a later chat provider should use `agy acp`; the docs must state Google's position on third-party hosts. +- External: https://antigravity.google/docs/cli/reference/ (flag spellings, re-read in Task 3.1). +- Research: done as the report above. Not run at planning time: nothing was installed, and no `agy` binary exists in CI or the labs. + +## Stack and commands + +- Web (React, Vite+, Vitest): focused test `cd apps/web && node ../../scripts/run-local-vp.mjs test run --project unit ` (from `apps/web/package.json` `test`). Not run at planning time; the suite is long. +- Server and desktop (Rust): `cargo test -p bibcode-server `, `cargo test -p bibcode-desktop ` (from the package `test` scripts; on Windows through `node scripts/run-msvc.mjs`), `cargo fmt --all --check`, `cargo clippy -p bibcode-server -p bibcode-desktop --all-targets -- -D warnings`. +- Contracts: `vp run check:contracts` (regenerates `packages/contracts/fixtures` and fails on an unstaged fixture diff). +- Repository gates: `vp check`, `vp run typecheck`, `vp run check:markdown-links` (which skips `docs/plans/**`). +- Packaged desktop UI: `vp run test:ui:desktop:build`, then `vp run test:ui:desktop`; `BIBCODE_E2E_SPEC=./specs/` runs one spec and `BIBCODE_E2E_PROFILER=1` turns the Profiler on for the run (`apps/desktop/e2e/wdio.conf.ts`, `apps/desktop/e2e/support/test-project.ts`). + +## Phases + +| Phase | File | Goal | Round | Depends on | Tier | +| ----- | -------------------------------------------- | ---------------------------------------------------------------- | ----- | ---------- | ------------ | +| 1 | phases/PHASE-01-files-undo-shortcuts.md | Undo and redo chords and the Edit menu drive the Files history | 1 | none | most capable | +| 2 | phases/PHASE-02-git-manager-remote-delete.md | Remote branch delete in Git Manager, with guard names that agree | 1 | none | most capable | +| 3 | phases/PHASE-03-antigravity-terminal.md | Antigravity instance and terminal, terminal-only | 1 | none | most capable | +| 4 | phases/PHASE-04-integration.md | Review, follow-up fixes, gates on the final commit, pull request | 2 | 1, 2, 3, 5 | standard | +| 5 | phases/PHASE-05-view-pr-panel.md | View PR opens the PR/MR panel | 1 | none | standard | + +Phases in the same round run in parallel. A phase depends only on phases in earlier rounds. + +## File map + +| Path or external change | Action | Phase | Verification | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | ----- | ----------------------------------------------------------------------- | +| `docs/plans/2026-11-20-undo-remote-delete-antigravity/diagnosis-398.md` | create | 1 | filled matrix | +| `apps/desktop/e2e/specs/files-undo-shortcuts.e2e.ts`, `apps/desktop/e2e/wdio.conf.ts` | create, modify | 1 | `vp run test:ui:desktop` | +| `apps/web/src/components/files/useFileHistoryInput.ts` and its test | create (Task 1.2 branch A or B) | 1 | focused web test | +| `apps/web/src/components/files/FilePreviewPanel.tsx` | modify | 1 | focused web test | +| `apps/web/src/components/files/fileUndoChords.test.tsx` | create | 1 | itself | +| `apps/web/src/components/files/FileEditorToolbar.tsx` and its test | modify | 1 | focused web test | +| `apps/desktop/src-tauri/src/window.rs`, `apps/web/src/components/AppSidebarLayout.tsx`, `docs/plans/2026-11-20-edit-menu-undo-design.md`, `docs/architecture/overview.md` | modify or create, only on Task 1.2 branch B | 1 | `cargo test -p bibcode-desktop menu`, review record | +| `docs/user/keybindings.md` | modify | 1 | `vp check` | +| `apps/web/src/components/gitManager/gitManagerGuardOperations.ts` | create | 2 | focused web test | +| `apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.tsx`, `toolbar/GitManagerBranchDropdown.tsx`, `GitManagerToolbar.tsx`, `GitManagerPanel.tsx` and their tests | modify | 2 | focused web test | +| `apps/web/src/components/gitManager/toolbar/remoteBranchRef.ts` and its test | create | 2 | focused web test | +| A shared sign-in-aware operation hook under `apps/web/src/components/gitManager/` | create | 2 | focused web test | +| `apps/server/src/git/manager/refs.rs`, `apps/server/src/git/manager/operations.rs`, `apps/server/src/git/repository.rs` | modify | 2 | `cargo test -p bibcode-server refs`, `... operations`, `... repository` | +| GitHub issue for the guard-name mismatch | create | 2 | `gh issue view` | +| `docs/plans/2026-11-20-antigravity-terminal-design.md` | create | 3 | review record | +| `packages/contracts/src/settings.ts`, `packages/contracts/src/model.ts`, `packages/contracts/fixtures/**` (regenerated) | modify | 3 | `vp run check:contracts` | +| `apps/server/src/server_settings/mod.rs`, `apps/server/src/production/control.rs` | modify | 3 | `cargo test -p bibcode-server server_settings`, `... control` | +| `apps/server/src/production/provider_inventory.rs` | modify | 3 | `cargo test -p bibcode-server provider_inventory` | +| `apps/server/src/production/provider_runtime.rs` | modify | 3 | `cargo test -p bibcode-server provider_runtime` | +| `apps/server/src/hermetic_guard.rs`, `apps/server/tests/support/hermetic_providers.rs`, `apps/server/src/test_support/mod.rs` | modify | 3 | `cargo test -p bibcode-server hermetic` | +| `apps/web/src/components/chat/providerTerminalActions.ts`, `providerAgentActions.ts`, `providerIconUtils.ts`, `apps/web/src/providerInstances.ts`, `apps/web/src/providerModels.ts`, `apps/web/src/threadProviderBinding.ts`, `apps/web/src/session-logic.ts` and their tests | modify | 3 | focused web test | +| `apps/web/src/components/settings/providerDriverMeta.ts`, `SettingsPanels.tsx`, `ProviderInstanceCard.tsx`, `apps/web/visual/typography/**` | modify | 3 | focused web test | +| `docs/providers/antigravity.md` | create | 3 | `vp run check:markdown-links` | +| `docs/providers/README.md`, `docs/architecture/providers.md`, `docs/README.md` | modify | 3 | `vp run check:markdown-links` | +| `apps/web/src/components/SourceControlPanel.tsx`, `GitActionsControl.logic.ts`, `SourceControlPrimaryAction.logic.ts` and their tests | modify | 5 | focused web test | +| `docs/user/workspace-ui.md`, `docs/testing/**`, `docs/plans/README.md` | modify | 4 | `vp check` | +| Follow-up GitHub issues and their fixes | create | 4 | `gh issue list` | + +Shared files reserved for the executor: `progress.md`, lockfiles. +Parallel conflicts: none between round 1 phases, which own disjoint files: phase 1 `apps/web/src/components/files/`, `apps/desktop/`, `AppSidebarLayout.tsx` and `docs/user/keybindings.md`; phase 2 `apps/web/src/components/gitManager/`, `apps/web/src/components/gitSignIn/` and the three Git server files listed; phase 3 `packages/contracts/`, the provider files listed and its docs; phase 5 the three Source Control files, which no other phase edits. Three things are shared and are serialized by the executor's build lock (one lock file in the Git common directory, taken before and released after each such command by the lane that runs it; a workflow coordinator hands out the slot, an inline executor runs them in sequence anyway): every `cargo` build (one target directory per lane worktree, one build at a time), the packaged desktop build (it rewrites `apps/web/dist`), and `vp run check:contracts` (it rewrites the fixtures, which only phase 3 may commit). + +## Traceability + +| Requirement | Tasks | +| ----------- | ------------- | +| R1 | 1.2, 1.3 | +| R2 | 1.2, 1.3 | +| R3 | 1.3 | +| R4 | 1.3 | +| R5 | 1.1, 1.2 | +| R6 | 2.3 | +| R7 | 2.2, 2.3 | +| R8 | 2.3 | +| R9 | 2.1 | +| R10 | 3.1 | +| R11 | 3.2, 3.4 | +| R12 | 3.4 | +| R13 | 3.3, 3.4 | +| R14 | 3.2, 3.5 | +| R15 | 2.1, 4.1, 4.2 | +| R16 | 5.1 | + +## End-to-end verification + +All six run on the commit that is pushed, and its SHA is logged with the results. + +1. `vp check` exits 0. +2. `vp run typecheck` exits 0. +3. `cargo fmt --all --check` exits 0, and `cargo clippy -p bibcode-server -p bibcode-desktop --all-targets -- -D warnings` exits 0. +4. `vp run -r --concurrency-limit 1 test` exits 0. +5. `BIBCODE_E2E_PROFILER=1 vp run test:ui:desktop` passes on the packaged build, with `files-undo-shortcuts.e2e.ts` named in the run report; the Profiler data has no new finding. +6. `gh issue list --repo mubeda/BibCode --state open` shows no follow-up of this work without a fix commit. + +## Risks + +- Issue #398's stated cause is wrong: both editors already bind the chords. The real failure is unlocated -> Task 1.1 reproduces it per platform before any fix, and stops with a question to the reporter if nothing reproduces. +- A menu-level fix (Task 1.2 branch B) changes undo for the whole app -> it needs its own reviewed design note and tests that the composer and plain text fields keep their undo, and it stops with a Ruling if that cannot be kept. +- Windows and Linux native paths need the labs; a locked Mac screen hides the E2E webview -> platforms not measured are named in the report, never assumed. +- The Antigravity driver has many registration sites -> Task 3.1 classifies every hit of one `rg` command, and review finding 8's list is the floor. +- No `agy` binary in CI or the labs -> launch is proven by command construction with fixtures, as #399's acceptance criteria ask; a live TUI start is not claimed. +- Google's terms discourage third-party tools on consumer plans -> the terminal only runs the user's own unmodified CLI, and the provider guide states the position; the later chat provider is out of scope. +- The research could not confirm every flag spelling from the primary page -> Task 3.1 step 1 re-reads the CLI reference before code depends on them. + +## Decisions + +- P1. Four parallel phases, one per issue (#400 was added by the owner during planning as phase 5), then one integration phase. Alternatives: one sequential phase (slower, and there is no file conflict to avoid). Decided by: agent's call. +- P2. The client adopts the server's emitted guard names instead of renaming them on the server. Alternatives: rename on the server (changes `blocked_reason_for_operation`, reasons visible over MCP, and eight tests). Decided by: agent's call. +- P3. No web hook for the undo chords is planned up front; the failure is located first. Alternatives: bind a capture-phase hook on the panel (the first draft; the editors already bind the chords, and the hook would have intercepted the comment textarea). Decided by: plan review 1, finding 6. +- P4. Outline and plan approval follow the owner's standing rule that a plan reviewed by Codex and the advisor counts as approved. Alternatives: wait for a chat yes at each gate. Decided by: user (standing rule). +- P5. Skills: every task has an installed skill; no gap, no install. +- P6. Execution continues on the branch this plan was written on, recorded in `progress.md`, not on a new branch cut from `main`. Decided by: agent's call. +- P7. Spec decisions D1, D5, D7 and D9 are the planning agent's calls where the issues left a choice, as are P10 and D12, and D8 follows issue #399's recommendation. The research report advised against a silent permission bypass, but Orca passes the same flag to `agy` by default (research addendum), as BiBCode's other terminals do, so D8 stands; a per-agent permission setting would be a separate issue. The pull request lists all five for the owner. +- P9. A later Antigravity chat provider uses ACP (`agy acp`), because no SDK fits. Decided by: user, 2026-11-20 ("use ACP if not available"), in line with the research and with Orca. +- P8. The client marks a remote default from each remote's local `HEAD` ref as an early reason only, an ambiguous remote name blocks Delete, and the server decides (P10). Alternatives: a contract change carrying remote and branch separately (larger, touches fixtures phase 3 owns). Decided by: agent's call. +- P10. The server is the authority for every remote branch delete (the new UI, the MCP tool, and local delete with "also delete from its remote"): it names `refs/heads/` explicitly, and one `ls-remote --symref` call before the push refuses the remote's default branch, an unreadable default, and a branch that differs from the local tracking ref. Alternatives: client-side checks only (plan review 2 showed they can target the wrong ref or miss a stale default); refusing any non-standard fetch mapping (it would refuse single-branch clones). This changes the behavior of an existing operation and of the MCP tool, not its contract. Decided by: agent's call, prompted by plan review 2 findings 1 and 3; listed for the owner. +- P11. A workflow lane starts from the plan's branch after the plan folder is committed, and a dependent task's lane starts from its predecessor's commits. + +## Appendix: questions record + +- 2026-11-20 Evidence: `apps/server/src/git/manager/guards.rs:172-198` emits `checkout`, `delete-branch`, `rename-branch`; the dialogs and dropdown look up `branch-*` names / Decision: R9, Task 2.1. +- 2026-11-20 Evidence: `@pierre/diffs/dist/editor/command.js` binds `cmdOrCtrl+z`, `cmdOrCtrl+shift+z`, `ctrl+y` / Decision: P3; Task 1.1 diagnoses first. +- 2026-11-20 Evidence: `apps/server/src/git/manager/refs.rs:315-346` sets `is_default` for local refs only / Decision: Task 2.2. +- 2026-11-20 Evidence: `GitManagerPanel.tsx:498-523` owns the sign-in offer; the toolbar runner has none / Decision: Task 2.3 shares one hook. +- 2026-11-20 Evidence: `provider_runtime.rs:6975-6985` already rejects an unknown driver with a generic message / Decision: Task 3.3 adds a specific refusal before it. +- 2026-11-20 Evidence: `research-antigravity.md` / Decision: no SDK; terminal now, `agy acp` later; terms stated in the guide (R14). +- 2026-11-20 Q: where, which spec, external sources, reviewer model / Recommended: this folder, the three issues, the issue links, Codex `gpt-6.2-sol` at `high` / Decision: recommended defaults taken without asking, per the owner's autopilot rule. diff --git a/docs/plans/2026-11-20-undo-remote-delete-antigravity/progress.md b/docs/plans/2026-11-20-undo-remote-delete-antigravity/progress.md new file mode 100644 index 000000000..c246717e9 --- /dev/null +++ b/docs/plans/2026-11-20-undo-remote-delete-antigravity/progress.md @@ -0,0 +1,33 @@ +# Progress: Files undo shortcuts, remote branch delete, Antigravity terminal + +Plan: plan.md +Spec: spec.md (sha256 9d9513bbe595) +Plan status: Approved 2026-11-20 +Plan review: Codex gpt-6.2-sol at high, round 2, Needs rework; all 25 findings of both rounds handled (reviews/), no third round +Executor: none +Branch: claude/backlog-triage-planning-pr-b5ee7f + +| Task | Title | Phase | State | Owner | Note | +| ---- | ----------------------------------------------------------------------------- | ----- | ----- | ----- | ---- | +| 1.1 | Reproduce the failure and locate it per platform | 1 | Open | | | +| 1.2 | Fix the located path and prove it in the packaged app | 1 | Open | | | +| 1.3 | Pin the chord behavior in web tests and correct the tooltip | 1 | Open | | | +| 2.1 | Make the dialogs and the dropdown read the server's guard names | 2 | Open | | | +| 2.2 | Mark each remote's default branch on the server | 2 | Open | | | +| 2.3 | Delete a remote branch from the branch list | 2 | Open | | | +| 3.1 | Write and review the Antigravity terminal design note | 3 | Open | | | +| 3.2 | Register the antigravity driver in settings, inventory and the hermetic lists | 3 | Open | | | +| 3.3 | Refuse a chat start for an Antigravity instance on the server | 3 | Open | | | +| 3.4 | Offer Antigravity Terminal and never an Antigravity chat in the client | 3 | Open | | | +| 3.5 | Document the Antigravity terminal | 3 | Open | | | +| 4.1 | Integrate, review and fix follow-ups | 4 | Open | | | +| 5.1 | Route View PR to the panel and keep a browser menu item | 5 | Open | | | +| 4.2 | Gate the candidate commit and open the pull request | 4 | Open | | | + +## Log + +- 2026-11-20 08:15 Plan written from issues #397, #398, #399. Outline and questions took the recommended defaults (plan.md, P4). +- 2026-11-20 08:30 Plan review 1 (Codex) and an advisor review processed. Undo is diagnosed before any fix, the remote default comes from the server, sign-in is shared with the toolbar, Antigravity registration and chat routing widened, gates moved to the final commit. +- 2026-11-20 08:33 Research report on the Antigravity CLI and SDKs added as research-antigravity.md, with an addendum on how Orca launches it. +- 2026-11-20 08:36 Issue #400 (View PR opens the browser) filed at the owner's request and planned as phase 5. +- 2026-11-20 08:50 Plan review 2 (Codex) and a second advisor review processed; corrections folded into the tasks. The round 2 fixes were not reviewed again. diff --git a/docs/plans/2026-11-20-undo-remote-delete-antigravity/research-antigravity.md b/docs/plans/2026-11-20-undo-remote-delete-antigravity/research-antigravity.md new file mode 100644 index 000000000..7af14c01b --- /dev/null +++ b/docs/plans/2026-11-20-undo-remote-delete-antigravity/research-antigravity.md @@ -0,0 +1,76 @@ +# Launching Antigravity now, wrapping ACP later + +Launch Google's Antigravity CLI (`agy`) as an AI Terminal now, and build the chat-panel provider later on `agy acp` rather than on any SDK. The terminal path is low-risk: `agy` is a self-contained Go binary installed by a curl or PowerShell script, so BiBCode needs no Node or Python and only has to spawn it in a PTY with the project as the working directory ([Getting started](https://antigravity.google/docs/getting-started?tab=cli)). The chat path has a clear transport, `agy acp`, an official ACP v1 server over stdio shipped in CLI 1.5.0 ([ACP page](https://antigravity.google/docs/cli/acp.md)). Neither route fits the official SDK, which is a Python package (`google-antigravity`, Alpha, version 0.1.24) that bundles a compiled runtime and has no Rust or TypeScript counterpart ([PyPI](https://pypi.org/project/google-antigravity/)). The two real risks are not technical. First, Google's terms and FAQ forbid third-party tools from accessing Antigravity on consumer plans, and no Google text clearly approves BiBCode's use ([FAQ](https://antigravity.google/docs/faq)). Second, ACP is about 16 days old with many open bugs ([issue list](https://github.com/google-antigravity/antigravity-cli/issues?q=acp)). Most observation signals (hooks, status line) require editing the user's own config files, so the terminal integration should stay a plain launcher at first. Most evidence below comes from docs read through a summarizing fetch tool, so exact flag spellings should be re-checked against `agy --help` before they ship. Nothing was installed or run. + +## One binary name, two install paths + +The CLI installs with `curl -fsSL https://antigravity.google/cli/install.sh | bash` on macOS and Linux, placing `agy` in `~/.local/bin`. On Windows it uses `irm https://antigravity.google/cli/install.ps1 | iex` in PowerShell or an `install.cmd` script, which installs `agy.exe` ([Getting started](https://antigravity.google/docs/getting-started?tab=cli)). The official docs put the Windows directory at `%LOCALAPPDATA%\agy\bin` ([Troubleshooting](https://antigravity.google/docs/cli/troubleshooting)). A third-party guide reports `%LOCALAPPDATA%\Antigravity\agy.exe` ([guide](https://pasqualepillitteri.it/en/news/3422/antigravity-cli-agy-install-migrate-gemini-cli)). The same guide mentions a compatibility alias `antigravity-cli.cmd`, which no official source confirms. No official npm, Homebrew or winget package for the CLI was confirmed. A search summary attributed winget to the Flutter docs, but the page itself did not contain it. The installer accepts `--skip-path` and `--skip-aliases` (it otherwise purges legacy `agy` and `antigravity` shell aliases) ([Authenticate docs](https://antigravity.google/docs/install?tab=cli)). The CLI self-updates (`agy update`), and `AGY_CLI_DISABLE_AUTO_UPDATE=true` turns that off ([Troubleshooting](https://antigravity.google/docs/cli/troubleshooting)). One issue reports the background updater renaming `~/.local/bin/agy` mid-session ([#1670](https://github.com/google-antigravity/antigravity-cli/issues)). Releases are near-daily, with 1.5.13 on 2026-11-19 the latest seen ([releases](https://api.github.com/repos/google-antigravity/antigravity-cli/releases?per_page=5)). + +The name clash is real but only partly documented. The Antigravity IDE historically shipped a launcher also called `agy`. A Gemini CLI issue shows distributions shipping `antigravity` without `agy` ([gemini-cli#15553](https://github.com/google-gemini/gemini-cli/issues/15553)), and a Firebase Tools change moved IDE detection from `agy` to `antigravity` ([PR 10063](https://github.com/firebase/firebase-tools/pull/10063)). A Google codelab snippet mentions an "agy-ide command line tool", which suggests the IDE launcher was renamed, but that is a single snippet and no version is confirmed ([codelab](https://codelabs.developers.google.com/getting-started-agy-ide)). A third-party guide describes a Homebrew `antigravity` formula installing `antigravity` into `/opt/homebrew/bin` and the CLI installing `agy` into `~/.local/bin`, with PATH order deciding which `agy` wins. Practically, BiBCode must not trust the name. It should resolve every `agy` candidate on PATH plus the documented install locations, run `agy --version` on each (the safe probe; `agy version` can fail without a TTY per a community source), and accept only the one whose output looks like the CLI. It should also run `agy --help` once to confirm the expected flags exist. This also lets a user point BiBCode at an absolute path, which the ACP docs recommend for editors because GUI processes often have a thinner PATH than a shell. + +## The launch command and what the first run asks + +The flags below come from the official CLI reference ([reference](https://antigravity.google/docs/cli/reference)). Running `agy` with no subcommand starts the interactive TUI in the current directory. + +| Flag | Meaning and version notes | +| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--version` | Verifies the install; the probe BiBCode should run. | +| `--model ` | Slugs come from `agy models`; the full list is not published. Gemini 4 Neon was added in 1.5.13. | +| `--effort` | "low through max (depends on model)"; an older cheat sheet (1.2.4) listed only low, medium, high. | +| `--mode accept-edits\|auto\|plan` | `auto` needs 1.3.5+ on macOS and Linux and 1.4.4+ on Windows. Since 1.5.7 the default agent mode is Auto. | +| `-c`, `--continue` | Resume the most recent conversation. It reads `~/.gemini/antigravity-cli/cache/last_conversations.json`, keyed by workspace path ([Resume doc](https://antigravity.google/docs/cli/commands/resume.md)). | +| `--conversation ` | Resume a specific conversation. Stable, unlike `-c`, which can pick another terminal's session. | +| `--dangerously-skip-permissions` | Auto-approves all tool permission requests. | +| `--sandbox` | OS containment; since 1.4.4 it has no effect if unavailable. | + +Other useful flags are `--add-dir` (repeatable), `--agent`, `-i`/`--prompt-interactive`, `--project`, `--new-project` and `--log-file` ([reference](https://antigravity.google/docs/cli/reference)). Permission posture is otherwise a settings concern: `toolPermission` (`request-review` by default, `proceed-in-sandbox`, `always-proceed`, `strict`), `trustedWorkspaces`, and rule entries like `command(git)`. Because the default mode became Auto in 1.5.7 (users can restore Default with `"agentMode": ""`), an unflagged launch behaves differently across versions. BiBCode should therefore pass `--mode` explicitly only when the user chose one, and otherwise leave the CLI's own default alone. + +First launch asks for a colour scheme, a rendering mode (Alt-Screen or Inline) and workspace trust ([Getting started](https://antigravity.google/docs/getting-started?tab=cli)). These prompts appear inside the embedded terminal, so BiBCode should not try to answer them. It should render them like any other TUI and document that the first run per workspace is interactive. The `altScreenMode` setting (`default|always|never`) controls rendering, and `AGY_CLI_DISABLE_AUTO_UPDATE` is the one environment knob worth setting if the host wants a stable binary during a session. Sign-in opens a browser, or prints a URL over SSH. Credentials go to the OS keyring (Windows Credential Manager, a macOS Keychain item named "Antigravity CLI"), and WSL falls back to token files ([Troubleshooting](https://antigravity.google/docs/cli/troubleshooting); [README](https://github.com/google-antigravity/antigravity-cli)). That means a terminal-first integration needs no credential handling at all: the user signs in inside the PTY. + +## Signals a host can observe, and what each costs + +The documented status signals fall into two groups: those BiBCode can read without touching the user's configuration, and those that need an edit to shared files under `~/.gemini`. In the first group is the terminal byte stream itself. Version 1.4.0 added terminal status reporting over OSC 7501 (working, waiting, done, failed), and 1.5.10 fixed a "done" shown while background work was still running ([CHANGELOG](https://raw.githubusercontent.com/google-antigravity/antigravity-cli/main/CHANGELOG.md)). A third-party release aggregator adds that the CLI queries the terminal for support first, and that `AGYCLIOSC7501=on|off` and `AGYCLIOSC7501MESSAGES=brief` exist ([release note](https://www.havoptic.com/r/antigravity-cli-1.4.0)). The exact payload, the query format, and whether those variables are official are unconfirmed, so BiBCode should record the raw OSC 7501 and BEL bytes during the first experiments rather than design a parser. The `notifications` setting, off by default, rings the terminal bell and raises a desktop notification when the agent needs approval or an answer, or finishes its turn ([Settings](https://antigravity.google/docs/settings.md)). + +The second group is richer but invasive. A `statusLine` command in `~/.gemini/antigravity-cli/settings.json` runs on each agent-state change (at most every 300 ms, 5 s timeout, disabled after 30 consecutive failures) and receives JSON with `conversation_id`, `transcript_path`, `agent_state` (`idle`, `working`, `tool_use`, `reviewing`, `authenticating`, `initializing`, `error`) and `tool_confirmation_pending` ([Statusline doc](https://antigravity.google/docs/cli/statusline.md)). That last field is the only documented machine-readable "waiting for approval" signal besides OSC 7501 and the bell. A `title` script receives the same payload ([Title doc](https://antigravity.google/docs/cli/title.md)). Hooks have six events (`SessionStart`, `PreToolUse`, `PostToolUse`, `PreInvocation`, `PostInvocation`, `Stop`) read from `.agents/hooks.json` or `~/.gemini/config/hooks.json`, and their stdin carries `conversationId` and `transcriptPath` ([Hooks doc](https://antigravity.google/docs/hooks.md)). There is no notification, permission-request or prompt-submit event, and no per-launch flag or environment variable for supplying hooks. Community tools such as workmux derive working and done from `PreInvocation` and `Stop` with `fullyIdle:true`, and they show no waiting state ([workmux](https://workmux.dev/guide/status-tracking.md)). Session transcripts live under `~/.gemini/antigravity-cli/brain//.system_generated/logs/transcript.jsonl`, but the file may not exist yet and its schema is undocumented. The config root is shared with Gemini CLI and the IDE, so any BiBCode edit there affects other tools. + +## Headless and ACP: two programmatic doors, one clearly better + +Headless mode is documented in depth ([Headless](https://antigravity.google/docs/cli/headless.md)). `agy -p` runs one prompt and exits. `--output-format stream-json` emits NDJSON with an `init` event, many `step_update` events and a `result`. A true multi-turn mode runs without `-p`, using `--input-format stream-json` with `{"event":"user","message":{"content":"..."}}` lines on stdin. That mode has no tool-permission round trip, since approvals are policy-based and unobtainable ones are denied with exit 0. Reliability is the problem: a `-p` hang without a TTY was reported on 1.2.0, 1.2.3 and Windows 1.4.10 and closed as obsolete without a confirmed fix ([#318](https://github.com/google-antigravity/antigravity-cli/issues/318)), and an earlier silent-stdout-loss bug was closed in July ([#76](https://github.com/google-antigravity/antigravity-cli/issues/76)). Headless is suitable for BiBCode's one-shot utility calls but not for a permissioned chat panel. + +`agy acp` is the right chat transport. It speaks ACP protocol version 1 over stdio as "Antigravity ACP Server", and editors launch it with command `agy` and args `["acp"]` ([Other editors (ACP)](https://antigravity.google/docs/ide/extensions/acp/)). Flags after `acp` include `--add-dir`, `--agent`, `--sandbox`, `--dangerously-skip-permissions`, `--process-per-session` (needed for HTTP MCP servers the client supplies), `--login`, `--log-file` and `--disable-telemetry`. Logs go to `~/.gemini/antigravity-cli/log/acp-*.log`. A real initialize response from 1.5.9 shows `loadSession:true`, prompt capabilities for images and embedded context but not audio, session capabilities for resume, close, load, list and additional directories, and a logout capability. It also shows duplicate snake_case keys, no `mcpCapabilities`, and no `authMethods` in the reported excerpt ([#1604](https://github.com/google-antigravity/antigravity-cli/issues/1604)). The docs list five auth method ids: `oauth-personal`, `oauth-business`, `gemini-api-key`, `agent-platform` and `terminal-login`. Unauthenticated calls fail with JSON-RPC `-32000` "Authentication required", and `agy acp --login` runs a code-paste sign-in that also works over SSH. Reuse of credentials cached by an interactive `agy` session is documented. + +The version history is short. Third-party tracking dates `agy acp` to 1.5.0 (4 Nov 2026), "every model works in any ACP client" to 1.5.1, and Auto mode plus session fixes to 1.5.4 ([release tracker](https://www.havoptic.com/releases/antigravity-cli/2026/11)). The docs state no minimum version and only say to run `agy acp --help`. A sensible gate is 1.5.4 or later. The open bugs matter more than the version. Provider failures (401, 429, 504, dropped streams) end `session/prompt` with `stopReason: end_turn` and the error only as warning text in a message chunk, so quota exhaustion looks like a normal reply ([#1570](https://github.com/google-antigravity/antigravity-cli/issues/1570)). `session/load` replays no history ([#1672](https://github.com/google-antigravity/antigravity-cli/issues/1672)), and `session/list` can return desktop-app sessions that then fail with `-32603` "trajectory not found". `authenticate` can open a browser even with a valid token, and with no display it fails with `-32603` "No browser is available here" ([#1637](https://github.com/google-antigravity/antigravity-cli/issues/1637)). A subagent's `run_command` can time out without ever asking permission ([#1658](https://github.com/google-antigravity/antigravity-cli/issues/1658)). Sessions can wedge after an `ask_question` plus load ([#1581](https://github.com/google-antigravity/antigravity-cli/issues/1581)). ACP also failed on ARM Linux hosts with a 39-bit address space, which Google staff called known (forum thread below). Compared with `cursor-agent acp` and `gemini --acp`, the lifecycle is the same, so an existing ACP client needs only per-provider command, auth ids and extension handling. + +## SDKs do not fit, and the terms fit the terminal better than the panel + +The official SDK is `google-antigravity` on PyPI: Apache-2.0, Alpha, Python 3.10+, 25 releases since May 2026, with platform wheels that carry a compiled runtime binary ([PyPI](https://pypi.org/project/google-antigravity/)). It uses the same harness as the CLI and the Antigravity 2.0 app ([SDK launch blog](https://www.antigravity.google/blog/introducing-google-antigravity-sdk)), but it authenticates only with `GEMINI_API_KEY` or Agent Platform (Vertex) credentials, and no consumer sign-in is documented. TypeScript and Go are roadmap items only, and Google's maintainers closed a request to host a Node port in the main repository ([issue #31](https://github.com/Google-Antigravity/antigravity-sdk-python/issues/31)). A community Rust crate reportedly drives the bundled `localharness` Go binary, but no wire protocol is documented ([docs.rs snippet](https://docs.rs/crate/antigravity-sdk-rust/0.1.4/source/justfile)). Embedding it would mean shipping Python or reverse-engineering an undocumented protocol. The other official surfaces do not help either. Managed Agents in the Gemini API run in Google's cloud sandbox with no local file access, are in preview, and are billed per token ([docs](https://aistudio.google.com/docs/custom-agents)). `@google/genai` (3.6.1) is only a model client. Gemini CLI is now an enterprise and API-key product (consumer access ended 18 June 2026), is Node-based, and has no official SDK package: `@google/gemini-cli-sdk` returned a 404 ([announcement](https://developers.googleblog.com/an-important-update-transitioning-gemini-cli-to-antigravity-cli/)). Community ACP adapters such as `agy-acp` scrape the CLI's conversation database, and their own disclaimer warns of terms-of-service risk. + +The terms are the sharpest constraint, and Google's own materials conflict. The terms treat using the service "in connection with products not provided by us" as grounds for suspension ([terms](https://antigravity.google/terms)). The FAQ says third-party tools accessing Antigravity violate the terms, and that wrapping `agy` in third-party coding agents "isn't supported on consumer plans", pointing such users to Gemini Enterprise or an AI Studio API key ([FAQ](https://antigravity.google/docs/faq)). Yet the headless and ACP docs invite programmatic use and describe five editors doing exactly that. A forum reply written on Google's behalf on 2 November 2026 said the official, unmodified ACP server is supported for single-user interactive development and compliant use "will not cause a suspension", while custom wrappers and non-ACP integrations must use an API key or Enterprise ([forum](https://discuss.ai.google.dev/t/197131)). An earlier reply of unverified staff status lists proxying OAuth tokens, wrapping `agy -p` in agent loops and account rotation as suspension triggers ([forum](https://discuss.ai.google.dev/t/192027)). Reports of 403 "disabled for violation" after OAuth-proxy tools exist ([forum](https://discuss.ai.google.dev/t/code-403-message-this-service-has-been-disabled-in-this-account-for-violation-of-terms-of-service/128101)). The terminal integration is the safest reading: BiBCode is only a terminal emulator, and the user runs Google's own TUI and signs in themselves. A chat panel built on `agy acp` is the pattern the staff reply tolerates, but whether a distributed desktop app counts as "single-user interactive development" is not established. Quotas also stay shared with the user's other use and are not predictable ([plans](https://antigravity.google/docs/plans)). + +## Windows and cross-platform differences + +Windows differs in install directory (the reports conflict), in `--mode auto` (1.4.4+ instead of 1.3.5+), and in many quoting fixes: hook commands containing double quotes (1.5.8), `!` command quoting (1.5.9), and `EDITOR` paths with backslashes (1.5.8) ([CHANGELOG](https://raw.githubusercontent.com/google-antigravity/antigravity-cli/main/CHANGELOG.md)). An open issue reports that `run_command` subprocesses share the TUI's console and can write stderr over it ([#1690](https://github.com/google-antigravity/antigravity-cli/issues)), which is a ConPTY-adjacent risk for an embedded terminal. The sandbox blocks reads of `AppData\Roaming` since 1.5.10, and the status line and hooks run via `cmd /c` on Windows rather than `sh -c`. No document covers TERM or truecolor requirements, ConPTY behavior, or standard proxy environment variables. macOS and Linux share the curl installer, and Linux adds the ARM 39-bit address-space ACP failure noted above. Because all of these are reported rather than tested, the terminal launcher should be validated once per platform before the integration is called supported. + +## Recommendations + +For the terminal integration, add an "Antigravity" AI Terminal that spawns the resolved absolute path of `agy` with no arguments, in a PTY, with the project directory as working directory. Pass flags only for explicit user choices: `--model`, `--effort`, `--mode`, and either `--conversation ` or `-c` for resume. Do not pass `--dangerously-skip-permissions` or `--sandbox` by default, and never inject them silently. Before first launch, run `agy --version` and `agy --help` on every candidate to filter out the IDE launcher, and offer a path override. Probe and record, on each platform, the first-run prompts, the raw OSC 7501 and BEL output with and without `AGYCLIOSC7501=on`, and what the TUI does on resize. Document the shared `~/.gemini` config root, the first-run prompts, sign-in inside the terminal, the version-dependent default mode, the update behavior, and the consumer-plan terms warning. Do not edit `settings.json`, `hooks.json` or MCP configs without explicit consent, do not store, read or proxy Google credentials or keyring entries, do not rotate accounts, do not scrape `conversations/` or the transcript database, and do not wrap `agy -p` as a general agent loop. If status is wanted early, prefer passive OSC 7501 and BEL detection over a hook or status-line install, and treat a consented `statusLine` command as a later opt-in. + +For the later chat provider, speak ACP v1 to `agy acp [--add-dir ...]` over stdio, reusing the generic ACP client that handles other providers, and configure only the command, auth method ids and the `ask_question` extension. Require 1.5.4 or later, check `agy acp --help` at startup, and handle both camelCase and snake_case capability keys. Assume `authMethods` may be missing: on `-32000`, send the user to an interactive `agy` or `agy acp --login` in an embedded terminal rather than silently opening a browser. Persist BiBCode's own transcript because load and resume replay nothing. Scan agent message text for provider and quota errors, because the stop reason will not report them. Filter out foreign sessions from `session/list`. Use `--process-per-session` only if BiBCode must pass HTTP MCP servers. Exclude the SDK, Managed Agents and Gemini CLI paths. Offer API-key and Agent Platform credentials as the officially supported alternative for users on consumer plans, and obtain a written answer from Google before shipping the chat provider to the public. + +## Open questions and conclusion + +Several points remain unconfirmed. The install page and changelog were partly read through summaries, so flag spellings, the Windows install directory and any winget, npm or Homebrew packages for the CLI are unverified. No official source names the version in which the IDE launcher was renamed, or says how `agy` and the IDE launcher behave when both are installed. The OSC 7501 payload, the query handshake and the official status of the `AGYCLIOSC7501*` variables are undocumented. Hook exit-code semantics, hook environment variables, whether `.agents/hooks.json` needs workspace trust, and the transcript and conversation file formats are unknown. The ACP method names for model, mode and plan updates are not confirmed from raw traces. The ACP minimum version rests on a third-party tracker rather than the official changelog. Whether the non-TTY `-p` hang affects stdin-stream mode on current versions, and whether the Zed registry's `agy_acp_server` binary differs from the `agy acp` subcommand, are open. The exact text and effective date of the terms, and whether a commercial desktop host qualifies for Google's tolerated ACP use, are also unresolved. + +The takeaway is that the integration choice is dominated by policy and maturity, not by capability. The terminal path is nearly free technically and the safest on terms, so it should ship first with the host staying passive. The chat path is technically ready enough through `agy acp`, but a 16-day-old protocol surface, silent error reporting and an unanswered terms question make it a staged, version-gated, bring-your-own-credentials feature, not a default. + +## Addendum: how Orca launches Antigravity (read 2026-11-20) + +Source: the public `stablyai/orca` repository, `main` branch, read on 2026-11-20. + +- Terminal: the detect and launch command is `agy` (`src/shared/agent-launch/catalog/tui-agent-config.ts`). The permission flag for its "full access" choice is `--dangerously-skip-permissions` (`src/shared/agent-launch/permissions/tui-agent-permissions.ts`), the same table that gives Claude `--dangerously-skip-permissions` and Codex `--dangerously-bypass-approvals-and-sandbox`. +- The flag is a visible setting, not hard-coded. Each agent has a permission choice: `own` (no flag, the agent's own configuration), `ask`, `accept-edits`, `auto` or `full-access` (`tui-agent-permission-choice.ts`). An untouched install is on `full-access` for every agent (`agent-launch-permission-seed.ts`), so by default Orca does pass the flag to `agy`. +- Orca writes Antigravity's workspace trust before launch, because the TUI's trust menu would otherwise swallow a pasted prompt (`tui-agent-config.ts`, `preflightTrust`). +- Chat: Orca uses ACP, not an SDK. It runs the host's `agy acp` when its version is at least 1.5.2, adding `--dangerously-skip-permissions` for full access, and otherwise a managed ACP server (`src/main/antigravity/antigravity-acp-launch-spec.ts`, `antigravity-host-acp.ts`). It lists models with `agy models`. +- Its setup guide tells users to confirm `agy --version`, to enter a full path when the CLI is not found, and to keep flags out of the command field (`docs/site/content/docs/agents/antigravity.mdx`). + +What this settles for BiBCode: passing `--dangerously-skip-permissions` by default matches Orca's default and BiBCode's other terminals. Orca's difference is that the user can change it per agent; BiBCode has no such setting for any terminal today. diff --git a/docs/plans/2026-11-20-undo-remote-delete-antigravity/reviews/plan-review-1.md b/docs/plans/2026-11-20-undo-remote-delete-antigravity/reviews/plan-review-1.md new file mode 100644 index 000000000..4525b9c62 --- /dev/null +++ b/docs/plans/2026-11-20-undo-remote-delete-antigravity/reviews/plan-review-1.md @@ -0,0 +1,82 @@ +# Plan review 1 + +Reviewer: Codex gpt-6.2-sol, effort high, read-only, 2026-11-20. Output unchanged below. + +Verdict: **Needs rework.** The plan assigns all 15 requirements, but following it as written can expose the wrong remote branch to deletion, skip the required sign-in flow, and pass packaged desktop validation without running the new spec. Phase 3 also has a Cargo command that fails before collecting tests and misses registration and chat-routing paths needed for a terminal-only provider. + +## Coverage + +This review uses the latest `spec.md` checksum, `19d19bd8567f`. Phase filenames below are relative to the plan folder. + +| Requirement | Tasks | Coverage and gaps | +| -------------------------------------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| R1 · Source undo, redo, empty history and toolbar sync | 1.1, 1.2 | **Partial.** Add a real Pierre baseline and assert toolbar state after each action, including default prevention with empty history. | +| R2 · Rendered Markdown undo and redo, one step | 1.1, 1.2 | **Partial.** The two-history-entry test covers undo. Include redo and a formatting transaction in the behavioral checks. | +| R3 · Ctrl+Y by platform and accurate tooltip | 1.1, 1.2 | **Partial.** The resolver matrix covers the policy. Exercise both editor views and account for TipTap’s existing `Mod-y` binding when checking the tooltip. | +| R4 · Focus scope and Save | 1.1, 1.2 | **Gap.** The outer capture hook can intercept an inline comment textarea. Branch B also changes the native shortcut path outside Files. Keep an end-to-end Save assertion. | +| R5 · Native shortcuts and Edit menu | 1.2, 4.1 | **Gap.** The native probe covers macOS source Undo only, and the default packaged suite omits the new spec. | +| R6 · Confirmed remote delete, local branch retained, remote-only branch, refreshed row | 2.2 | **Partial.** The planned request and revalidation checks should assert that the row disappears from a refreshed snapshot, for both a same-named local branch and a remote-only branch. | +| R7 · Remote default and symbolic HEAD protection | 2.2 | **Gap.** No task supplies authoritative defaults per remote. The blocked-row test checks accessible description but leaves the visible reason and submission refusal unproven. | +| R8 · Sign-in and protected-branch error | 2.2 | **Gap.** The toolbar has no sign-in presentation or resume path. The generic error test does not prove that a Git rejection reaches the dialog. | +| R9 · Local guard names and remote delete during operations | 2.1, 2.2 | **Partial.** Name correction is assigned. The test can pass before the rename fix. Keep the latest D5 decision and add regression evidence that remote delete remains allowed in the five named states. | +| R10 · Reviewed Antigravity design | 3.1 | **Assigned.** The advisor approval and design-file link check need executable instructions. | +| R11 · Disabled-by-default Settings instance, `agy` probe, CLI sign-in, no observer | 3.2, 3.3 | **Partial.** Add persisted enable/path tests and a live-shaped inventory-to-Settings fixture. | +| R12 · Terminal launch in checkout, conditional flags, activity and no resume flags | 3.3 | **Partial.** Command cases are assigned. The raw defaults path and a complete terminal-open fixture are missing. | +| R13 · Chat omission, fallback and server refusal, existing editor launch | 3.2, 3.3 | **Gap.** Shared menu filtering covers several pickers. Other chat fallback paths and the early server refusal need explicit tests. The existing editor launch is correctly outside scope. | +| R14 · Hermetic guard and linked provider guide | 3.2, 3.4 | **Partial.** The guide is assigned. The shared hermetic settings fixture also needs registration. | +| R15 · Follow-ups, quality gates, reviews, runbooks, profiler and one PR | 2.1, 4.1 | **Partial.** The final reviewed commit can differ from the tested commit. Review and publication instructions disagree across files. | + +Every numbered task serves a requirement. The `ccd_pr` binding in Task 4.1 is the one execution step with no stated acceptance purpose or available tool in this session. The latest spec’s decisions on Ctrl+Y, remote delete during in-progress operations, disabled-by-default Antigravity, and omitted chat actions are binding for this review. The non-goals stay outside scope. + +## Findings + +| # | Severity | Location (file:line) | Issue | Evidence | Fix | +| --- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1 | Blocker | `PHASE-02-git-manager-remote-delete.md:39–52` | Remote Delete can enable the wrong row or resolve the wrong destination. | `apps/server/src/git/manager/refs.rs:315–346` sets `isDefault` only on local refs and omits `*/HEAD`. `apps/server/src/git/repository.rs:6229–6267` derives one default from `origin/HEAD`, local `main`/`master`, or the current branch. Comparing that one name across all remotes can enable deletion of `upstream/trunk` when it is upstream’s default and disable an ordinary `upstream/main`. `refs.rs:411` strips `refs/remotes/`, leaving a name ambiguous when both `team` and `team/fork` are configured. The proposed `origin-fork` test never exercises that ambiguity. | Expand Phase 2 ownership to the server ref reader and tests. Supply per-remote default evidence and retain the exact remote and branch identity. Define the unavailable or ambiguous metadata behavior before enabling Delete. Test two remotes with different defaults, unknown defaults, symbolic HEAD and slash-prefix ambiguity. Revalidate the target at confirmation. | +| 2 | Blocker | `PHASE-02-git-manager-remote-delete.md:50–52` | The existing toolbar runner cannot deliver R8 as written. | `GitManagerToolbar.tsx:338–371` records a failure message and revalidates refs. `apps/web/src/state/gitManager.ts:35–52` only streams the operation. `GitManagerPanel.tsx:498–523,1048–1054` owns sign-in and retries `offer.resume`. The server can emit that offer for remote delete and freezes the destination in the resume request (`operations.rs:1316–1323,1340–1360,1430–1447`). Ordinary Git failures are classified into a summary, with command output carried separately (`operations.rs:2238–2258`). | Reuse the sign-in presenter and resume flow in the toolbar path. Assert initial `_tag`, `cwd`, `projectId`, `remote`, `branch`, and that retry preserves optional `expectedDestination`. Test declined sign-in, resumed success and a protected rejection with the Git error visible in the still-open dialog. | +| 3 | Blocker | `PHASE-03-antigravity-terminal.md:45–54` | Task 3.2’s red and green commands cannot run as specified. | I invoked Cargo with the listed filters and `--offline`. It rejected `server_settings` as an unexpected argument before building. Even separate versions of those three filters would omit the `provider_runtime` refusal test. `package.json:33` regenerates fixtures and checks their worktree diff, so a changed fixture can fail the instructed pre-commit green run. | Give each Rust test target or filter its own invocation, including the refusal, and use the repository’s `run-msvc.mjs` wrapper where needed (`apps/server/package.json:9`, `docs/reference/scripts.md:93–101`). Specify fixture generation, review, staging and parity-check order. | +| 4 | Major | `PHASE-01-files-undo-shortcuts.md:53–63` | The three menu branches are neither exclusive nor sufficient across platforms. | The app installs predefined Edit roles (`apps/desktop/src-tauri/src/window.rs:116–124`). Pinned `muda 0.19.3` uses responder actions on macOS (`platform_impl/macos/mod.rs:977–986`), injects Ctrl+Z/Ctrl+Y on Windows (`platform_impl/windows/mod.rs:1208–1209,1264–1292`), and omits those predefined items on GTK (`platform_impl/gtk/mod.rs:30–43`). A menu `beforeinput` event plus a swallowed chord satisfies both A and B. The probe also uses one seeded edit for two Undo attempts and checks neither native Redo nor the rendered view. Branch B’s `execCommand` fallback has no demonstrated equivalence to the composer’s Lexical `HistoryPlugin` (`ComposerPromptEditor.tsx:2099`). | Use independent, freshly seeded native chord and menu cases for each view and direction. For A, require a cancellable event reaching the correct editor and one history transition. For B, reuse the existing `DesktopBridge.onMenuAction` channel (`packages/contracts/src/ipc.ts:1394`, `tauriDesktopBridge.ts:666`) and prove existing non-Files undo behavior. For C, record both successful native paths. Define Linux menu handling explicitly and check Windows/Linux regardless of the macOS branch selected. | +| 5 | Major | `PHASE-01-files-undo-shortcuts.md:43–54`; `PHASE-04-integration.md:30–31` | The integrated packaged run can pass without executing the new spec. | `apps/desktop/e2e/wdio.conf.ts:50–84` enumerates the default specs and uses `BIBCODE_E2E_SPEC` for a focused override. Phase 1 neither owns that config nor updates its list. The Profiler is seeded at test setup by `BIBCODE_E2E_PROFILER=1` (`apps/desktop/e2e/support/test-project.ts:1504–1506`), so putting it on the build is insufficient. | Add the spec to the allowlist or extend the already-listed Files spec. Give the focused command using `BIBCODE_E2E_SPEC=./specs/files-undo-shortcuts.e2e.ts`, set the Profiler variable on the test invocation, and check the run report for the named cases. | +| 6 | Major | `PHASE-01-files-undo-shortcuts.md:24–35` | The capture mechanism works, but its proposed focus boundary and red tests are too broad. | Pierre listens on the inner content element, under an open shadow root, and already supplies Cmd/Ctrl+Z, Shift+Cmd/Ctrl+Z and Windows/Linux Ctrl+Y (`@pierre/diffs/dist/components/File.js:454`, `dist/editor/editor.js:874–878,953–969`, `dist/editor/command.js:5–12,42–49`). TipTap has its own history bindings (`@tiptap/extensions/dist/index.js:688–690`). The outer panel also contains an autofocus comment textarea (`FilePreviewPanel.tsx:677–689`, `LocalCommentAnnotation.tsx:54–76`). The specified red command omits `FilePreviewPanel.test.tsx`. | A composed `keydown` can cross Pierre’s shadow boundary and reach an ancestor before the editor handlers. Scope it to the actual editing host using the composed path, or bind at the two editor surfaces with one shared policy. `EditableFileSurface` owns the source ref (`FilePreviewPanel.tsx:446–470`), while `LoadedRichMarkdown` owns the rendered save ref and `RichMarkdownSurface` creates the editor (`RichMarkdownView.tsx:47–54`, `RichMarkdownSurface.tsx:84–107`). Include the panel in the focused command and prove a behavior fails before the change beyond a missing import. [W3C UI Events](https://w3c.github.io/uievents/#event-type-keydown) | +| 7 | Major | `PHASE-02-git-manager-remote-delete.md:29–33` | The planned rename test can be green before the fix, and checkout can still use unrelated guards. | The server emits `checkout`, `delete-branch` and `rename-branch` (`guards.rs:173–198,305–320`, `operations.rs:1104–1118`). A rename-only fixture already works through `branch.blocked[0]` (`GitManagerBranchDialogs.tsx:315–329`). The dropdown’s predicate can still select a `merge` or `rebase` dirty reason after correcting the checkout string (`GitManagerBranchDropdown.tsx:145–174`), preventing the dirty checkout dialog from opening (`GitManagerToolbar.tsx:444–453`). | Use mixed guard arrays and assert the action’s specific reason. Test a valid rename with unrelated reasons, dirty checkout reaching Stash/Bring, worktree redirects, and real checkout blocks. Preserve the `branch-checkout` **request tag**. | +| 8 | Major | `PHASE-03-antigravity-terminal.md:39–54,60–73` | The registration list misses production and fixture sites. | Both server settings readers use `built_in_provider_defaults` (`server_settings/mod.rs:14,66,335`, `production/control.rs:2976–3013`), but production patch validation enumerates drivers separately (`control.rs:2817–2841`). Inventory needs both the synthesized roster and the built-in check (`provider_inventory.rs:278–314,2059–2064`). Its snapshot uses the Rust display-name path, which would stamp lowercase `antigravity` and override the web label (`provider_inventory.rs:2015–2023`, `provider_runtime.rs:2532–2543`, `providerInstances.ts:84–86`). The hermetic fixture list and enabled table are outside the allowlist and their parity test will fail (`apps/server/tests/support/hermetic_providers.rs:26–29,61–76`, `apps/server/src/test_support/mod.rs:133–147`). | Name those files and update the exact-order inventory assertion at `provider_inventory.rs:2919–2922`. Cover fresh, partial, and explicit settings plus disabled, successful and failed probes. On web, include the Settings card and defaults wiring (`SettingsPanels.tsx:2077–2117`, `ProviderInstanceCard.tsx:771–779`) alongside driver metadata and the icon map. `ProviderDriverKind` is open, so no new closed-union member is needed (`packages/contracts/src/providerInstance.ts:16–32`). | +| 9 | Major | `PHASE-03-antigravity-terminal.md:31,70–76` | The design correctly calls for explicit defaults, but the implementation step only adds a branch to a function that receives normalized defaults. | `providerTerminalActions.ts:119–124,169–184` passes a resolved model and effort. With an empty catalog, the resolver substitutes a generic fallback model and yields null effort without capability descriptors (`packages/shared/src/providerSessionDefaults.ts:89–96,242–254,303–337`). The settings value has `model` and optional `options`, and the current Settings control disables model selection with no catalog (`packages/contracts/src/settings.ts:571–578`, `ProviderSessionDefaultsControls.tsx:42–46`). | Feed Antigravity’s explicit model and recognized effort option from the raw settings value into terminal argv. Suppress the misleading catalog fallback for this driver. Test absent defaults, model alone, model plus effort, an oversized argv value and the normal terminal-open path with fixture cwd and activity. Google documents both flags for interactive sessions, with model-dependent effort levels. [Google CLI reference](https://antigravity.google/docs/cli/reference/) · [Google effort reference](https://antigravity.google/docs/cli/commands/effort) | +| 10 | Major | `PHASE-03-antigravity-terminal.md:10,31,71–73` | Filtering the action list leaves independent chat-routing paths open. | The panel menu and worktree chooser consume `buildProviderAgentActions` (`ChatHeaderPanelMenu.tsx:171–173`, `CreateWorktreeDialog.tsx:370–383`), and terminal reviewers already have a separate allowlist (`codeReview.ts:116–123`). But `resolveDefaultAgentInstanceId` can return the excluded saved ID on null (`providerAgentActions.ts:103–113`), and the Files and Add Project callers persist it (`FileBrowserPanel.tsx:421–443`, `useAddProjectWorkflow.ts:1024–1045`). Composer fallback separately picks the first enabled snapshot (`providerModels.ts:96–105`, `ChatView.tsx:2438–2445`). Server routing resolves the instance’s driver and rejects unknown drivers before the factory (`provider_runtime.rs:6734–6737,6975–6985`), with a generic setup message (`:2470–2473`). | Apply a shared chat-eligibility rule at the actual fallback owners. Test a saved Antigravity chat with no other ready instance, and preserve an explicitly selected terminal. Put the clear server refusal before generic canonicalization, test a custom instance ID through the chat caller, and assert no spawn. | +| 11 | Major | `plan.md:96–97`; `PHASE-02-git-manager-remote-delete.md:6–7`; `PHASE-04-integration.md:6,33` | Required ownership and shared-build dependencies are missing. | Phase 2 needs ref-source ownership for R7. `docs/user/workspace-ui.md:1224–1243` still says remote rows offer checkout only, while Task 3.4 owns the same document. `docs/architecture/providers.md:3–12` needs the new supported mode and disabled default. In one checkout, the desktop build consumes and rewrites `apps/web/dist` (`tauri.conf.json:8–11`), and Phase 3 writes contract fixtures (`package.json:33`). The plan names an executor build lock without specifying how lanes acquire it. | Assign the shared workspace guide to Phase 4 with edges from 2.2 and 3.4. Give Phase 3 the provider architecture and fixture files. Specify lane checkouts and output roots, or serialize shared build/fixture writers. Keep the existing string-valued menu bridge if it suffices so Phase 1 can stay clear of Phase 3’s contracts. | +| 12 | Major | `PHASE-04-integration.md:28–36`; `execute-plan.md:31,72–99` | The publication sequence can ship a commit whose fixes were never gated. | Task 4.1 runs gates and the packaged suite before its follow-up fixes and final review. The inline runner repeats broad checks before another review, while `docs/skills/issue-delivery/SKILL.md:20–32` calls for proof on the reviewed candidate. Task 4.1 says to push and open a PR, while the execute wrapper reserves publication for explicit authorization. The diff also uses local `main`, which was 20 commits behind local `origin/main` in this checkout. | Put review, issue/fix reconciliation and the final candidate commit before final gates. Name the complete-caller proof required by `scripts/check-agent-delivery.mjs:29–32` and log the tested SHA. Use a verified PR base and one authorization-aware publication step. Track each follow-up issue against its fix commit. | +| 13 | Minor | `PHASE-01-files-undo-shortcuts.md:43–63`; `PHASE-02-git-manager-remote-delete.md:19,38–52`; `PHASE-03-antigravity-terminal.md:25–33,39–60`; `plan.md:144` | Task size, handoffs and skills need a final pass. | Task 1.2 combines platform diagnosis, a conditional architecture design, implementation and packaged proof. Task 3.2 bundles settings, discovery, hermetic checks and chat admission, then runs workspace typecheck before the consuming UI task. Task 2.2 has no stated consumer of the new guard constants, although it shares files with 2.1. Task 3.1’s Markdown check excludes `docs/plans/**` (`package.json:34`). `rust-best-practices` and the advisor tool are absent from this session’s inventory, and `mstack-decisions` is a meeting-notes skill (`mstack-decisions/SKILL.md:3–8`). | Split native diagnosis from the selected implementation and proof. Give settings/probe and chat admission separate behavioral checkpoints, and gate shared types on the combined slice. Keep 2.1 → 2.2 as a file-ordering edge. Verify the design note by path, name the review host and Rust skill gap, and add expected outputs for the shell probes and phase lint/format commands referenced by `execute-plan.md:61–65`. | + +## What the plan got right + +- Keep the same history owners as the toolbar and leave Save on its existing hook. The toolbar already subscribes to the active rich editor and reads source history from the session. `FilePreviewPanel.tsx:898–914,1068–1075,1122–1126`, `fileEditingSession.ts:417–427`. +- Reuse the existing typed remote-delete operation and local confirmation pattern. The server already has a test proving deletion of the remote branch leaves its local namesake intact. `packages/contracts/src/gitManager.ts:205–214,252–258`, `GitManagerBranchDialogs.tsx:397–452`, `operations.rs:6085–6148`. +- Preserve the generic provider probe and terminal launch path. Inventory already invokes `--version`, and the existing panel handler forwards the structured terminal command. Codex and Claude remain the separate terminal-review allowlist. `provider_inventory.rs:731–747`, `ChatView.tsx:5004–5011`, `providerTerminalActions.ts:228–236`. +- The task IDs, titles and phase numbers match `progress.md:10–20`, and the spec checksum matches `plan.md:4` and `progress.md:4`. The three feature lanes can remain parallel after their ownership changes. The integration phase correctly depends on all three. + +## Open questions the plan cannot answer + +- Which native path does the packaged app actually take for Undo **and** Redo in each editor on macOS, Windows and Linux? The pinned source explains the different dispatch mechanisms. Runtime equivalence remains unverified. +- What is the intended user-visible behavior when a remote has no locally known default, or its tracking ref maps ambiguously to configured remotes? The design needs to settle this before exposing a destructive action. +- Which execution host can provide the required advisor review, and which `agy` versions will the launch tests qualify? Official documentation confirms the flags. No installed `agy` or native terminal launch was exercised. + +This was a read-only review. `gh issue view` could not reach GitHub, so the approved spec governed the review. I checked the spec checksum, repository status, branch refs and Cargo argument parsing. I did not run builds, test suites, or native UI checks. CodeGraph sync was skipped because it can write generated data. + +## Handling + +Every finding was checked against the code before it was accepted. + +1. Remote default and remote identity (Blocker): fixed. Verified at `apps/server/src/git/manager/refs.rs:315-346` (`is_default` is local-only, `*/HEAD` dropped). Phase 2 now owns the ref reader, the server marks each remote's default from `/HEAD`, and ambiguous or unknown cases have a decided behavior (Tasks 2.2, 2.3). +2. Sign-in path (Blocker): fixed. Verified at `GitManagerPanel.tsx:498-523`: the panel owns the sign-in flow, the toolbar runner does not. Task 2.3 reuses that flow in the toolbar path and tests declined, resumed and rejected cases. +3. Cargo filters (Blocker): fixed. One filter per `cargo test` invocation, the refusal test included, fixture order stated (Tasks 3.2, 3.3). +4. Edit menu branches (Major): fixed. Phase 1 starts with a diagnosis task with an ordered, exclusive decision rule per platform; branch B reuses `DesktopBridge.onMenuAction` (`packages/contracts/src/ipc.ts:1394`). +5. Packaged run skips the new spec (Major): fixed. Verified at `apps/desktop/e2e/wdio.conf.ts:50-78`. Phase 1 owns the allowlist; commands use `BIBCODE_E2E_SPEC` and `BIBCODE_E2E_PROFILER=1`. +6. Hook too broad, editors already bind the chords (Major): fixed, and it changes the premise. Verified in `@pierre/diffs/dist/editor/command.js`: `cmdOrCtrl+z`, `cmdOrCtrl+shift+z` and `ctrl+y` (Windows, Linux) are bound. Issue #398's guess that nothing binds them is disproved, so no web hook is planned up front; the failure is located first (Task 1.1). +7. Rename test green before the fix, checkout predicate (Major): fixed. Mixed guard arrays and the checkout cases are in Task 2.1. +8. Missing registration sites (Major): fixed. Tasks 3.2 and 3.3 name `production/control.rs`, the hermetic fixture lists, the display-name path and the Settings card files. +9. Model and effort from normalized defaults (Major): fixed. Task 3.4 reads the raw settings value. +10. Other chat-routing paths (Major): fixed. Task 3.4 applies one chat-eligibility rule at the fallback owners; Task 3.3 puts the server refusal before canonicalization. +11. Ownership and shared builds (Major): fixed. `docs/user/workspace-ui.md` moved to phase 4, `docs/architecture/providers.md` to phase 3, build lock rule stated in `plan.md`. +12. Publication order (Major): fixed. Phase 4 reviews and fixes first, then gates the final commit and logs its SHA; base is `origin/main`. +13. Task size, handoffs, skills (Minor): fixed where factual (tasks split, design note checked by path, `mstack-decisions` removed). Rejected in part: `rust-best-practices` and the advisor exist in the Claude Code session that executes the plan; the reviewer's own session lacked them. + +Open questions: the native path per platform is Task 1.1's output; unknown or ambiguous remote metadata is decided in Task 2.2; `agy` is not installed anywhere, so launch is proven by command construction only (plan Risks). diff --git a/docs/plans/2026-11-20-undo-remote-delete-antigravity/reviews/plan-review-2.md b/docs/plans/2026-11-20-undo-remote-delete-antigravity/reviews/plan-review-2.md new file mode 100644 index 000000000..b3584cc3b --- /dev/null +++ b/docs/plans/2026-11-20-undo-remote-delete-antigravity/reviews/plan-review-2.md @@ -0,0 +1,81 @@ +# Plan review 2 + +Reviewer: Codex gpt-6.2-sol, effort high, read-only, 2026-11-20. Output unchanged below. + +Verdict: **Needs rework.** The revised plan covers all 16 requirements by name, but the remote-delete path can target the wrong Git ref, and Phase 1 still cannot route several outcomes its own diagnosis can produce. Phase 3 leaves independent chat fallbacks open, and Phase 5 needs to distinguish a panel that can display the request from one that can only show an unavailable state. + +## Coverage + +`Phase 1` through `Phase 5` below refer to the five phase files in `docs/plans/2026-11-20-undo-remote-delete-antigravity/phases/`. “Gap” marks a scenario the assigned tasks do not reliably implement or prove. + +| Requirement | Tasks | Coverage | +| ------------------------------------------------------------------------------------------------ | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| R1 · Source Undo, Redo, empty history, toolbar state | 1.2, 1.3 | Assigned. **Gap:** diagnosis can observe a failing delivered keydown with no implementation branch. | +| R2 · Rendered Markdown Undo and Redo, one step, including formatting | 1.2, 1.3 | Assigned. **Gap:** the native fix only reruns previously failing cells, even when it replaces both accelerators. | +| R3 · Ctrl+Y by platform and complete tooltip | 1.3 | Both views and all three platforms are assigned. **Gap:** the macOS tooltip omits TipTap’s existing Cmd+Y binding. | +| R4 · Other focus targets and Save | 1.1–1.3 | Save, inline comments, and composer are assigned. **Gap:** Branch B lacks a concrete native fallback and a terminal focus check. | +| R5 · Packaged chords and Edit menu | 1.1, 1.2, 4.2 | **Gap:** mixed outcomes, absent menu items, unavailable hosts, and an all-pass baseline have no complete path to closure. | +| R6 · Confirmation, exact remote branch, local namesake retained, remote-only delete, refresh | 2.3 | Confirmation and both refreshed row scenarios are assigned. **Gap:** tests stop short of proving the Git destination. | +| R7 · Remote default and symbolic HEAD protection | 2.2, 2.3 | Known local remote-HEAD targets are assigned. **Gap:** stale or unknown defaults can be actionable, and the plan only tests filtering symbolic HEAD rows out. | +| R8 · Sign-in, protected-branch warning and rejection | 2.3 | Warning, decline, and resume payload are assigned. **Gap:** resumed success and the real streamed rejection are unproven. | +| R9 · Local guard reasons and remote delete during five in-progress states | 2.1, with 2.3 as consumer | Mixed guard arrays cover the naming fix. **Gap:** no task proves eligibility during the five named states. | +| R10 · Reviewed Antigravity design | 3.1 | All required design topics are assigned. The advisor invocation and review handoff need an executable route. | +| R11 · Settings instance, disabled default, `agy` probe, CLI sign-in, no observer | 3.2, 3.4 | Assigned. The probe failure fixture needs to distinguish an executable that exits nonzero from an executable that cannot start. | +| R12 · Terminal launch in checkout, binary override, conditional flags, activity, no resume flags | 3.4 | Command construction is assigned. **Gap:** no menu-to-terminal-open test proves checkout and payload together. | +| R13 · No chat choices or fallback, clear server refusal, existing editor launch | 3.3, 3.4 | Shared action filtering and server refusal are assigned. **Gap:** independent chat selectors can still pick Antigravity. | +| R14 · Hermetic guard and linked guide | 3.2, 3.5, 4.1 | Guard and guide are assigned. **Gap:** the AI Terminal notes are told to list Antigravity, while the spec requires a link to its guide. | +| R15 · Follow-ups, gates, reviews, runbooks, profiler and one PR | 2.1, 4.1, 4.2 | Assigned. **Gap:** the inline executor can alter the gated SHA and review after publication. | +| R16 · View PR/MR in panel, explicit browser action and browser fallback | 5.1 | Both Source Control ladders are assigned. **Gap:** unsupported server capability and component-level browser fallback are missing. | + +Every numbered task serves a requirement. The proposed panel routing in `GitActionsControl.tsx` is the one implementation step with no demonstrated user-facing caller. Its production mount hides the trigger and retains the component for branch synchronization. `apps/web/src/components/chat/ChatHeaderActions.tsx:184–193`. + +## Findings + +| # | Severity | Location (file:line) | Issue | Evidence | Fix | +| --- | -------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1 | Blocker | `PHASE-02-git-manager-remote-delete.md:77–80` | **Delete can target a different remote ref from the row the user confirmed.** | `refs.rs:408–424` exposes the local tracking name. A custom fetch refspec can map remote `release` to local `origin/topic`, so the proposed splitter can request deletion of an unrelated remote `topic`. Separately, `apps/server/src/git/repository.rs:4560–4575` pushes an unqualified `:name`. If the remote branch has disappeared and a same-named tag remains, Git can resolve that destination to the tag. The existing server test checks the local branch and remote branch lists only. `operations.rs:6085–6148`. [Git fetch ref mapping](https://git-scm.com/docs/git-fetch#_configured_remote_tracking_branches), [Git push refspec rules](https://git-scm.com/docs/git-push#Documentation/git-push.txt-ltrefspecgt). | Resolve the row through the configured fetch mapping or disable Delete when the mapping cannot be verified. Use an explicit `refs/heads/` destination in the existing operation. Add bare-remote regressions for an aliased tracking ref and a stale branch with a same-named tag. | +| 2 | Blocker | `PHASE-01-files-undo-shortcuts.md:26,38–43,60–67` | **Task 1.1 cannot always produce a decision Task 1.2 can execute.** | One failing cell can deliver cancellable `beforeinput` while another on the same platform delivers nothing. Selecting A first leaves the B cell unfixed. A failed delivered `keydown`, a non-cancellable event, and an unavailable lab have no branch. GTK also omits the predefined Undo and Redo items, which is a distinct observation from clicking an existing item and receiving no event. An all-pass result assigns C everywhere, then blocks 1.2 and therefore 4.1. `apps/desktop/src-tauri/src/window.rs:116–124`, pinned `muda` version at `Cargo.lock:3714–3717`, `muda-0.19.3/src/platform_impl/gtk/mod.rs:30–43`, `PHASE-04-integration.md:17`. | Record a disposition and follow-up per failing cell or group of cells with the same cause. Define outcomes for delivered keys, non-cancellable events, absent items, unavailable hosts, and a passing baseline. Give 1.2 a verified no-change completion path. | +| 3 | Major | `PHASE-02-git-manager-remote-delete.md:56–58,68,77–78` | **R7 still permits a remote default to reach confirmation.** | The plan uses a local symbolic ref and falls back to protecting the local default’s name. With local `main` and an added remote whose default is `trunk`, a missing or stale remote HEAD leaves `trunk` enabled. `GitManagerRefsSnapshot.defaultBranch` is a single value, and the proposed helper receives no remote rows with which to determine whether the selected remote has a known default. The operation itself checks the remote name and branch syntax. `packages/contracts/src/gitManager.ts:62–75`, `refs.rs:280–282,315–346`, `operations.rs:1595–1620`. [Git remote HEAD behavior](https://git-scm.com/docs/git-remote#Documentation/git-remote.txt-set-head). | Give the guard per-remote default status. Obtain reliable evidence or make unknown status a visible blocker. Recheck eligibility on Confirm and before a sign-in resume. Cover missing and stale HEAD, a row that becomes default while the dialog is open, and a symbolic HEAD row if one reaches the client. | +| 4 | Major | `PHASE-02-git-manager-remote-delete.md:78–80` | **The sign-in and rejection tests can pass while the dialog remains wrong.** | The panel’s wrapper resumes via `executeOperationRef` and discards its success value, while the toolbar closes the dialog in `submitBranchDialog` only after the original call returns success. Git rejection details arrive as `output` events before a separate `failed` summary. A mock that puts the Git refusal into `failed.message` bypasses that seam. `GitManagerPanel.tsx:505–523`, `GitManagerToolbar.tsx:345–371,485–525`, `apps/server/src/production/git_manager_rpc.rs:1264–1308`. | Route resumed completion back to the dialog that owns the request. Test decline, resumed success with close and refresh, and a protected rejection using `output(stderr)` followed by `failed`. | +| 5 | Major | `PHASE-03-antigravity-terminal.md:14,36,87–100` | **The listed chat filters leave independent fallback paths open.** | `ChatView` calls `resolveThreadProviderBinding`, which selects the first enabled snapshot on fresh threads. Sidebar’s default-thread creation and worktree adoption independently do the same. With Antigravity first or alone, the tests in 3.4 can pass while a new thread is assigned to a driver the server refuses. `ChatView.tsx:2243–2263`, `threadProviderBinding.ts:108–139,237–245`, `Sidebar.tsx:2389–2422`, `WorktreeDiscoverySection.tsx:79–98`. | Assign these callers and tests to 3.4. Apply the shared predicate where a chat is selected and prove that an enabled Antigravity instance first or alone cannot become an implicit chat target. Preserve explicit terminal selections. | +| 6 | Major | `PHASE-05-view-pr-panel.md:19,28–30` | **View PR can open a panel that permanently cannot display the request.** | The current `canOpenInPanel` checks the setting and provider kind. The actual surface independently requires `pullRequestsReads`. On a connected legacy server, that capability defaults to false, so the primary click would open an unsupported panel instead of the required browser fallback. Also, `open_pr_panel` currently belongs to menu types only, and `resolveQuickAction` has no panel argument. `SourceControlPanel.tsx:258,427–437`, `pullRequests/pullRequestsAvailability.ts:41–52`, `PullRequestPanelSurface.tsx:61–66,91–103`, `repositoryModule/repositoryModuleAvailability.ts:62–68`, `packages/contracts/src/environment.ts:62`, `GitActionsControl.logic.ts:19–33,180–185`, `SourceControlPrimaryAction.logic.ts:28–37,60–83`. | Extend both primary action types, pass the capability through the legacy resolver, and keep transient disconnect behavior distinct from permanent lack of support. Parameterize click tests across legacy and staging-area paths, with GitHub, GitLab, and browser fallback cases. Keep `GitActionsControl.tsx` out of the edit unless its hidden mount needs a compatibility change. | +| 7 | Major | `PHASE-04-integration.md:38,44,48–54` and `execute-plan.md:31,65–66,72–99` | **Inline execution can review too late and advance beyond the gated SHA.** | Task 4.2 logs evidence in tracked `progress.md` and pushes the candidate. The wrapper then requires a task-closing commit with `progress.md`, followed by another broad run and review that can produce more fixes. The wrapper also reserves publication for explicit authorization and expects phase branches even though inline execution uses one branch. | Use one sequence for both modes: integrate if needed, review, fix, commit, gate that SHA, then publish when authorized. Keep post-gate evidence outside that commit or gate the new commit. Put the final review before the gate in both modes. | +| 8 | Major | `PHASE-01-files-undo-shortcuts.md:50–67` | **Branch B still lacks a reproducible focus handoff and schedules approval too late.** | The existing menu channel emits a string and the sidebar listener handles updates and settings. A custom accelerator does not supply the prior edit action for a focused textarea, terminal, or Lexical composer. The plan says to fall through without defining that operation, and puts its design review after implementation. Rechecking only failed cells can miss regressions on paths the replacement changes. `window.rs:50–80,116–124`, `AppSidebarLayout.tsx:139–159`, `ComposerPromptEditor.tsx:2099`, `AGENTS.md:193–198`. | Review the dispatch design before editing. Give Task 1.2 exact focus routing and approved file ownership for each affected surface. Recheck previously passing cells and outside-Files behavior wherever accelerators change. | +| 9 | Major | `PHASE-03-antigravity-terminal.md:54–56,93–103` | **The Antigravity tests can verify the command builder without proving that the installed CLI can be launched from the menu.** | The existing menu constructs actions separately from `ChatView` forwarding a command and selecting the launch checkout. The generic full probe also treats a process that exits nonzero as installed with warning status, whereas 3.2 calls for a failed probe to mean “not installed.” A ready hand-built action fixture bypasses both seams. `ChatHeaderPanelMenu.tsx:171–173`, `ChatView.tsx:4868–4900,5004–5011`, `provider_inventory.rs:731–742`. | Add a production-shaped inventory-to-menu fixture, then click the action and assert the terminal-open checkout, command, and activity. Specify separate cases for an absent binary and a nonzero version probe. An inert executable fixture is sufficient for this check. | +| 10 | Major | `plan.md:105–106`, `PHASE-01-files-undo-shortcuts.md:25,50,72–85`, `PHASE-02-git-manager-remote-delete.md:46–58` | **The file map misses conflicts within Phase 1 and leaves the shared build lock unspecified.** | 1.3 has no dependency and can edit an editing host under its Ruling while 1.2 edits `FilePreviewPanel.tsx`. 1.2 writes the diagnosis record it only lists as input. Phase 2’s current ref command lacks the symbolic target and its parser expects five fields, so the one-call option needs `repository.rs` added to ownership. `apps/server/src/git/repository.rs:807–825`, `refs.rs:383–403`. The lock is named but acquisition and release are unspecified, including for the Cargo invocation inside `check:contracts`. `package.json:33`. | Order 1.3 after 1.2, or make any editor-host correction an explicitly owned prerequisite. List the diagnosis record, both real editor attachment points, and the selected ref-reader files. State how each lane gets the build slot and how predecessor commits reach dependent lanes. | +| 11 | Minor | `PHASE-01-files-undo-shortcuts.md:83–89`, `PHASE-03-antigravity-terminal.md:87–103`, `PHASE-04-integration.md:29` | **Several acceptance checks have the wrong expectation or command.** | TipTap’s `Mod-y` is Cmd+Y on macOS and the app retains StarterKit Undo/Redo, so an exact “Shift+Cmd+Z only” tooltip test can bless incomplete copy. `richMarkdownExtensions.ts:174–181`, `@tiptap/extensions/src/undo-redo/undo-redo.ts:75–80`. The web `unit` project includes only `src` tests, so appending `visual/typography` does not run the gallery suite. `apps/web/vite.config.app.mjs:42–46`, `docs/testing/typography-fixtures.md:8–18`. Phase 4 says to list Antigravity in the notes and never asks for the R14 link. | Verify actual chords per view and derive tooltip expectations from the supported policy. Use the standalone gallery command when its fixtures change. Make the workspace notes link to the guide and check the link. | +| 12 | Minor | `plan.md:156`, `PHASE-03-antigravity-terminal.md:34–37`, `PHASE-04-integration.md:3,19–21`, `execute-plan.md:10,29` | **The executor brief still has handoff and consistency gaps.** | The advisor may exist on the intended host, but 3.1 gives no invocation or Expected result for it. The linked CLI reference documents the launch flags but does not list `--version`. Phase 4 correctly depends on 5 while its goal and inputs still say three phases and omit the Phase 5 report. The executor also says three Round 1 phases. [Google CLI command reference](https://antigravity.google/docs/cli/reference/#command-line-flags). | Name the host’s advisor command, expected review artifact, and skill fallback. Give the flag check a source for `--version` or specify how to record it as unverified. Update the phase counts and report inputs, and give each compound shell step its working directory and Expected result. | + +## What the plan got right + +- Keep the diagnose-first approach. The source editor already handles the history keys, and the toolbar already distinguishes the two history owners. Retain the separate Save path, fresh history per native probe, and the new spec’s inclusion in the default packaged suite. `@pierre/diffs/dist/editor/editor.js:953–969`, `FilePreviewPanel.tsx:1068–1075,1122–1126`, `useFileSaveShortcut.ts:47–54`, `wdio.conf.ts:50–84`. +- Keep the existing typed remote-delete operation and confirmation pattern. The round-one mixed-guard and ambiguous-prefix cases are present in the phase file, and the planned sign-in resume preserves `expectedDestination`. Add the in-progress regression without changing D5. `packages/contracts/src/gitManager.ts:209–214,252–258`, `GitManagerBranchDialogs.tsx:397–452`, `guards.rs:10–51`. +- Keep the one-filter Cargo invocations, fixture staging order, raw session defaults for terminal arguments, and server refusal before driver canonicalization. Those are concrete round-one corrections. The spec’s permission flag, disabled default, CLI-owned sign-in, and editor-launch behavior govern the review. `package.json:33`, `providerTerminalActions.ts:163–185`, `provider_runtime.rs:6709–6737`, `packages/contracts/src/editor.ts:28`. +- Phase 5 can reuse the existing Source Control panel and browser dispatchers. Its stated file set has no direct write overlap with the other Round 1 phases. The plan checker passed with **5 phases, 14 tasks, and 16 requirements**, and the spec checksum matches both plan records. `SourceControlPanel.tsx:1021–1035,1070–1094`, `plan.md:65–69`, `progress.md:4,12–25`. + +## Open questions the plan cannot answer + +- Which native paths fail on each platform and view, and which lab sessions can prove them with real OS input? That evidence determines whether a bridge change is necessary. +- What evidence will the app use when a remote’s default is unknown or its tracking mapping cannot be verified? +- Which execution host will supply the advisor review, and will the approved plan and its handoff files be available in isolated worktrees? The plan folder is currently untracked. + +This was a read-only source and plan review at `3b74079286`. `gh issue view` could not reach GitHub for issues #397–#400, so the approved spec governed. The plan checker and checksum checks ran. Builds, test suites, native UI, Git deletion, and a live `agy` launch were unverified. CodeGraph sync was skipped because it can write generated files. No files were changed. + +## Handling + +Round 2 is the last review round. Every finding was checked against the code; each fix is in the phase file's "Binding corrections from plan review 2" "Rules for this task" block or steps of the task it concerns. + +1. Wrong remote ref (Blocker): fixed. Verified at `apps/server/src/git/repository.rs:4560-4575` (the push uses an unqualified `:name`). The server now names `refs/heads/` and refuses a custom fetch mapping (phase 2, plan P10, spec R7). +2. Diagnosis cannot always route (Blocker): fixed. Per-cell dispositions with six defined outcomes and a no-change completion path (phase 1). +3. Unknown or stale remote default (Major): fixed. The server checks the default with `ls-remote --symref` before deleting and refuses when it cannot (phase 2). +4. Sign-in and rejection tests (Major): fixed. Tests use `output` then `failed`, and the resumed completion is routed to the dialog (phase 2). +5. Independent chat fallbacks (Major): fixed. The predicate goes into `resolveThreadProviderBinding` and `resolveSelectableProvider`, with first-or-alone tests (phase 3). +6. Panel that cannot display the request (Major): fixed. The `pullRequestsReads` capability joins the check; `GitActionsControl.tsx` is left alone (phase 5). +7. Review after the gate, gated SHA moving (Major): fixed. One sequence, evidence in the PR body, a progress-only closing commit (phase 4). +8. Branch B design too late (Major): fixed. The design note comes before code and gives the focus routing; all cells are re-measured (phase 1). +9. Command builder tested without the menu path (Major): fixed. One production-shaped test; probe cases follow existing behavior (phase 3). +10. File map and build lock (Major): fixed. 1.3 depends on 1.2, the diagnosis record and the Git server files are owned, the lock is described (plan.md). +11. Wrong expectations and commands (Minor): fixed. Tooltip assertion loosened, gallery command corrected, the guide link required. +12. Handoff gaps (Minor): fixed. Advisor invocation and fallback named, `--version` source stated, phase counts corrected. + +No finding was rejected or deferred. A third review round was not run (the plan skill allows two). diff --git a/docs/plans/2026-11-20-undo-remote-delete-antigravity/spec.md b/docs/plans/2026-11-20-undo-remote-delete-antigravity/spec.md new file mode 100644 index 000000000..c32a721a1 --- /dev/null +++ b/docs/plans/2026-11-20-undo-remote-delete-antigravity/spec.md @@ -0,0 +1,125 @@ +# Spec: Files undo shortcuts, remote branch delete, Antigravity terminal + +Status: Approved 2026-11-20 (issues #397 to #400 are the owner's requests; open questions take each issue's recommended answer, recorded under Decisions) +Source: https://github.com/mubeda/BibCode/issues/397, https://github.com/mubeda/BibCode/issues/398, https://github.com/mubeda/BibCode/issues/399, https://github.com/mubeda/BibCode/issues/400, verified at `origin/main` 3b7407928. Triage: `triage.md`. + +## Goals + +1. Undo and redo work from the keyboard in the Files editor (#398). +2. A remote branch can be deleted from the Git Manager branch list (#397). +3. The AI Terminal menu can start the Antigravity CLI (`agy`) (#399). +4. View PR opens BiBCode's PR/MR panel (#400). + +## Requirements + +### R1. Source-view undo and redo chords + +- GIVEN the Files source editor has focus and one typed edit, WHEN the user presses Ctrl+Z (Windows, Linux) or Cmd+Z (macOS), THEN the edit is undone through the same history as the Undo button, exactly one step, and `canUndo` / `canRedo` on the toolbar stay in sync. +- GIVEN an undone edit, WHEN the user presses Shift+Ctrl+Z or Shift+Cmd+Z, THEN it is redone, exactly one step. +- GIVEN nothing to undo, WHEN the chord is pressed, THEN nothing changes and the event is still default-prevented. + +### R2. Rendered-Markdown undo and redo chords + +- GIVEN the rendered Markdown editor has focus and one text or formatting edit, WHEN the undo chord is pressed, THEN exactly one history step is undone (never two), and the redo chord restores it. + +### R3. Ctrl+Y redo + +- GIVEN Windows or Linux, WHEN Ctrl+Y is pressed in either Files editor view, THEN one step is redone. +- GIVEN macOS, WHEN Ctrl+Y is pressed, THEN the Files shortcut does nothing (D1). +- The Redo tooltip names every chord that works on the current platform. + +### R4. Scope of the chords + +- GIVEN focus outside the Files editor surface (chat composer, terminal, other panels), WHEN the chords are pressed, THEN behavior is unchanged from before. +- Ctrl/Cmd+S still saves. + +### R5. Desktop Edit menu + +- GIVEN the packaged desktop app with focus in a Files editor view, WHEN the user presses the chord or chooses Edit > Undo / Redo, THEN the Files editor history moves one step, or the plan records, with evidence from a packaged run, why the menu path is equivalent to the chord path. + +### R6. Delete a remote branch + +- GIVEN a remote branch row in the Git Manager branch list, WHEN the user chooses Delete and confirms in a dialog with the same required confirmation as local delete, THEN the client sends `remote-branch-delete` with that row's remote and branch name. +- GIVEN a local branch of the same name, THEN it is unchanged (D2). +- GIVEN a remote-only branch, THEN it can be deleted the same way. +- GIVEN a successful delete, THEN refs refresh and the row disappears. + +### R7. Remote default branch is blocked + +- GIVEN the remote row is known to be the remote's default branch, WHEN the user looks at its Delete action, THEN it is disabled with a visible reason, and no request can be sent (D3). +- GIVEN any remote delete request, THEN the server refuses to delete the remote's default branch, and refuses when it cannot check which branch that is. A symbolic `HEAD` row is never listed. +- The delete names the branch ref explicitly, so a tag of the same name is never deleted, and it is refused when the branch on the remote differs from what this checkout last fetched. + +### R8. Remote delete failures are visible + +- GIVEN missing credentials, THEN the existing sign-in path of #325 runs; GIVEN the remote refuses the push (for example a protected branch), THEN the dialog shows the Git error and stays open. The dialog text says the remote may refuse protected branches. No pull-request detection (D4). + +### R9. Guard names agree between server and client + +- GIVEN the server blocks deleting or renaming a local branch (current branch, default branch, held by a worktree), WHEN the Delete or Rename dialog opens, THEN it shows the server's reason. Today the server emits `delete-branch` / `rename-branch` and the dialogs look up `branch-delete` / `branch-rename`, so the reason never shows. +- `remote-branch-delete` stays allowed while a merge, rebase, cherry-pick, revert or squash is in progress (D5). + +### R10. Antigravity design note + +- A design note in `docs/plans/` settles: the driver slug, how a terminal-only instance appears in Settings, the permission flag, the model and effort source, every registration site, how chat is excluded on client and server, and the editor-catalog overlap. Review by Codex and the advisor counts as its approval (D6). + +### R11. Antigravity provider instance + +- GIVEN Settings > Agents, THEN an Antigravity instance can be added or enabled, with the existing Antigravity icon and a binary path that defaults to `agy` (never the driver slug). New installs have it disabled (D7). +- GIVEN an enabled instance, THEN the server probes it with `agy --version`; sign-in stays the CLI's own. No terminal observer. + +### R12. Antigravity Terminal launch + +- GIVEN an enabled instance and `agy` installed, WHEN the user picks Antigravity Terminal in the AI Terminal menu, THEN the TUI starts in the thread checkout as ` --dangerously-skip-permissions`, plus `--model ` and `--effort ` only when session defaults supply them, with `activity: { driverKind, providerInstanceId }` (D8). +- A configured binary path overrides `agy`. `--continue` and `--conversation` are never passed. + +### R13. Antigravity never looks chat-ready + +- GIVEN an Antigravity instance, THEN no chat action for it appears in the panel menu, the Default Agent picker, the code reviewer list or the worktree dialog, and it is never chosen as a fallback chat (D9). +- GIVEN a chat start that names an Antigravity instance, THEN the server refuses it with a clear error. +- "Open in Antigravity" (`agy --goto`) is unchanged. + +### R14. Antigravity cannot be spawned by unit tests, and is documented + +- `agy` is in the hermetic guard list. +- `docs/providers/antigravity.md` covers install (`agy --version`), sign-in (`agy`, or `agy acp --login` without a browser), the permission flag, the `agy` CLI versus IDE launcher PATH clash, and Google's stated position on third-party hosts for consumer plans; the provider index and AI Terminal notes link it. + +### R15. Follow-ups and gates + +- Every follow-up found while delivering R1 to R14 gets a GitHub issue and is fixed in the same pull request. +- `vp check`, `vp run typecheck`, `cargo fmt --all --check`, Clippy with warnings denied on changed targets, and focused tests pass. Changed React is reviewed against `vercel-react-best-practices`, changed UI against `UI.md`. Affected testing runbooks are reviewed. The report has a profiler coverage line. No credentials, real names, private hosts or local paths in commits, the PR or the docs. + +### R16. View PR opens the PR panel + +- GIVEN an open pull request and a panel that can open, WHEN the user clicks View PR (View MR on GitLab) in Source Control, THEN the PR/MR panel opens on that pull request and the browser does not. +- The menu offers "Open PR in browser", which opens the PR URL in the browser. +- GIVEN the panel cannot open, THEN View PR opens the browser, as before (D12). + +## Non-goals + +- A chat-panel driver for Antigravity (`agy acp`): a later issue. +- A terminal observer, resume flags, or retargeting "Open in Antigravity" to `agy-ide`. +- Pull-request detection before a remote delete. +- Deleting the local branch from the remote-delete dialog. + +## Decisions + +- D1. Ctrl+Y redoes on Windows and Linux only; on macOS Ctrl+Y is a text-system key. Source: #398 question 2 recommends Windows; adding Linux and excluding macOS is the planning agent's call, listed for the owner. +- D2. Remote delete leaves the local branch alone. Source: #397 question 1, recommended. +- D3. The remote default branch is blocked in the UI. Source: #397 question 2, recommended. +- D4. No pull-request detection in v1. Source: #397 question 3, recommended. +- D5. `remote-branch-delete` is not added to the operations blocked during an in-progress operation: `git push :` touches neither the index nor the working tree. Source: #397 question 4 leaves it open; the planning agent's call, listed for the owner. +- D6. The design note is required and is approved by Codex and advisor review. Source: #399 question 1, recommended yes; the owner's standing rule that reviewed designs count as approved. +- D7. A new Antigravity instance is disabled by default. Source: #399 proposed behavior offers this or enabled-but-unready; the planning agent's call, listed for the owner. +- D8. The permission flag is `--dangerously-skip-permissions`. Source: #399 question 2, recommended. +- D9. The chat action is omitted, not shown disabled. Source: #399 question 4 allows either; the planning agent's call, listed for the owner; the design note may change this to "disabled with a reason" only with evidence that omission is not possible. +- D10. Edit menu Undo and Redo drive the Files history when that surface has focus. Source: #398 question 3, recommended yes. +- D11. One pull request, base `main`. +- D12. View PR falls back to the browser where no panel can host the pull request. Source: issue #400, the planning agent's call, listed for the owner. + +## Verification + +1. Focused web tests for the Files chords, the Git Manager dialogs and dropdown, and the provider actions pass. +2. Focused server tests for guards, the provider inventory and the hermetic guard pass. +3. The packaged desktop UI suite passes with the Profiler on, including the new Files undo spec, and its Profiler data shows no new finding. +4. The gates in R15 pass. diff --git a/docs/plans/2026-11-20-undo-remote-delete-antigravity/triage.md b/docs/plans/2026-11-20-undo-remote-delete-antigravity/triage.md new file mode 100644 index 000000000..c676d721f --- /dev/null +++ b/docs/plans/2026-11-20-undo-remote-delete-antigravity/triage.md @@ -0,0 +1,9 @@ +# Triage, 2026-11-20 + +| Issue | Title | Class | Type | Recommendation | Route | Reason and evidence | Acceptance hint | Duplicate check | +| ----- | ----------------------------------------------------------------- | -------------- | ------- | -------------- | --------------------------- | ---------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | ------------------------------------- | +| #398 | Files: undo and redo keyboard shortcuts do not work in the editor | Bug with repro | bug | now | workflow | Complete report; only Ctrl/Cmd+S is bound on the Files surface | Chords undo and redo the same history as the buttons in both views | 3 searches, none (#342 related) | +| #397 | Git Manager: delete a remote branch from the branch list | Feature | feature | now | workflow | Server operation exists with no UI caller; guard names differ between server and dialogs | A remote row deletes after confirmation; default branch blocked; refused push shown | 3 searches, none (#139, #325 related) | +| #399 | AI terminal: support the Antigravity CLI | Feature | feature | now | workflow, design note first | No `agy` entry in the launch table, inventory or hermetic guard | Antigravity Terminal launches the TUI; chat action absent; editor command unchanged | 3 searches, none | + +Totals: 3 now, 0 next, 0 defer, 0 closing. From a17efc10fa3d0b971beac6ab5cca3e97c8a819a3 Mon Sep 17 00:00:00 2001 From: mubeda <1380447+mubeda@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:58:06 -0300 Subject: [PATCH 002/242] test(web): pin View PR to the panel and a browser menu item The tests fail until the action ladders return open_pr_panel for View PR. Co-Authored-By: Claude Fable 5.2 --- .../GitActionsControl.logic.test.ts | 89 ++++++++++++++++--- .../components/SourceControlPanel.test.tsx | 68 +++++++++++++- .../SourceControlPrimaryAction.logic.test.ts | 46 +++++++--- 3 files changed, 177 insertions(+), 26 deletions(-) diff --git a/apps/web/src/components/GitActionsControl.logic.test.ts b/apps/web/src/components/GitActionsControl.logic.test.ts index 4959e97ad..8341aebdb 100644 --- a/apps/web/src/components/GitActionsControl.logic.test.ts +++ b/apps/web/src/components/GitActionsControl.logic.test.ts @@ -75,7 +75,58 @@ describe("when: ref is clean and has an open PR", () => { assert.deepInclude(quick, { kind: "open_pr", label: "View PR", disabled: false }); }); - it("buildMenuItems offers opening the PR in the thread's panel only when asked", () => { + it("resolveQuickAction opens the PR in the panel when the panel can show it", () => { + const pr = { + number: 10, + title: "Open PR", + url: "https://example.com/pr/10", + baseRef: "main", + headRef: "feature/test", + state: "open", + } as const; + assert.deepInclude(resolveQuickAction(status({ pr }), false, false, true, true), { + kind: "open_pr_panel", + label: "View PR", + disabled: false, + }); + assert.deepInclude(resolveQuickAction(status({ pr }), false, false, true, false), { + kind: "open_pr", + label: "View PR", + }); + const gitlab = status({ + pr, + sourceControlProvider: { kind: "gitlab", name: "GitLab", baseUrl: "https://gitlab.test" }, + }); + assert.deepInclude(resolveQuickAction(gitlab, false, false, true, true), { + kind: "open_pr_panel", + label: "View MR", + }); + }); + + it("resolveQuickAction opens the PR in the panel when there is no upstream", () => { + const pr = { + number: 10, + title: "Open PR", + url: "https://example.com/pr/10", + baseRef: "main", + headRef: "feature/test", + state: "open", + } as const; + for (const hasPrimaryRemote of [true, false]) { + assert.deepInclude( + resolveQuickAction( + status({ hasUpstream: false, aheadCount: 0, pr }), + false, + false, + hasPrimaryRemote, + true, + ), + { kind: "open_pr_panel", label: "View PR" }, + ); + } + }); + + it("buildMenuItems puts View PR in the panel and keeps a browser item only when asked", () => { const withPr = status({ pr: { number: 11, @@ -86,20 +137,34 @@ describe("when: ref is clean and has an open PR", () => { state: "open", }, }); + assert.deepEqual( + buildMenuItems(withPr, false) + .filter((item) => item.icon === "pr") + .map(({ label, kind }) => ({ label, kind })), + [{ label: "View PR", kind: "open_pr" }], + ); + assert.deepEqual( + buildMenuItems(withPr, false, true, true) + .filter((item) => item.icon === "pr") + .map(({ label, kind, disabled }) => ({ label, kind, disabled })), + [ + { label: "View PR", kind: "open_pr_panel", disabled: false }, + { label: "Open PR in browser", kind: "open_pr", disabled: false }, + ], + ); assert.notInclude( - buildMenuItems(withPr, false).map((item) => item.id), - "pr_panel", + buildMenuItems(status(), false, true, true).map((item) => item.label), + "Open PR in browser", ); - assert.deepInclude(buildMenuItems(withPr, false, true, true).at(-1), { - id: "pr_panel", - label: "Open PR in panel", - disabled: false, - icon: "pr", - kind: "open_pr_panel", + const gitlab = status({ + pr: withPr.pr, + sourceControlProvider: { kind: "gitlab", name: "GitLab", baseUrl: "https://gitlab.test" }, }); - assert.notInclude( - buildMenuItems(status(), false, true, true).map((item) => item.id), - "pr_panel", + assert.deepEqual( + buildMenuItems(gitlab, false, true, true) + .filter((item) => item.icon === "pr") + .map((item) => item.label), + ["View MR", "Open MR in browser"], ); }); diff --git a/apps/web/src/components/SourceControlPanel.test.tsx b/apps/web/src/components/SourceControlPanel.test.tsx index 9b203a7f5..99c4a5032 100644 --- a/apps/web/src/components/SourceControlPanel.test.tsx +++ b/apps/web/src/components/SourceControlPanel.test.tsx @@ -135,6 +135,7 @@ const testState = vi.hoisted(() => ({ rightPanelOpen: vi.fn(), openPullRequest: vi.fn(), pullRequestsEnabled: true, + pullRequestsReads: true, selectGitScope: vi.fn(), toast: { add: vi.fn(), update: vi.fn(), close: vi.fn() }, groupByFolder: true, @@ -342,6 +343,7 @@ vi.mock("~/state/entities", () => ({ gitManagerStashMergeOperations: testState.mergeCapabilities, gitManagerBranchSyncOperations: testState.mergeCapabilities, codeReviews: testState.codeReviews, + pullRequestsReads: testState.pullRequestsReads, }, }, }), @@ -778,6 +780,7 @@ beforeEach(() => { testState.rightPanelOpen.mockReset(); testState.openPullRequest.mockReset(); testState.pullRequestsEnabled = true; + testState.pullRequestsReads = true; testState.selectGitScope.mockReset(); testState.toast.add.mockReset(); testState.toast.add.mockReturnValue("toast-1"); @@ -824,6 +827,14 @@ describe("SourceControlPanel", () => { expect(testState.runAction).toHaveBeenCalledTimes(1); }); + // A clean tree walks the remote ladder: the staging-area ladder, and the legacy one (files + // without an area) with its quick action. + const CLEAN_LADDERS = [ + status, + (overrides: Partial) => + legacyStatus({ hasWorkingTreeChanges: false, ...overrides }), + ]; + const OPEN_MR = { number: 89, title: "Fix it", @@ -840,7 +851,7 @@ describe("SourceControlPanel", () => { }); const props = buildProps(); render(props); - menuItemByText("Open MR in panel")?.onClick?.(); + menuItemByText("View MR")?.onClick?.(); expect(testState.openPullRequest).toHaveBeenCalledWith(props.threadRef, { number: 89, provider: "gitlab", @@ -848,6 +859,56 @@ describe("SourceControlPanel", () => { expect(testState.openPullRequestLink).not.toHaveBeenCalled(); }); + it("opens the open merge request in the panel from the View MR button, in both ladders", () => { + for (const build of CLEAN_LADDERS) { + testState.openPullRequest.mockClear(); + testState.statusQuery.data = build({ + sourceControlProvider: { kind: "gitlab", name: "GitLab", baseUrl: "https://gitlab.test" }, + pr: OPEN_MR, + }); + const props = buildProps(); + render(props); + const viewMr = buttonByExactText("View MR") ?? buttonsByText("View MR")[0]; + expect(viewMr).toBeDefined(); + viewMr?.onClick?.(); + expect(testState.openPullRequest).toHaveBeenCalledWith(props.threadRef, { + number: 89, + provider: "gitlab", + }); + expect(testState.openPullRequestLink).not.toHaveBeenCalled(); + } + }); + + it("opens the PR URL in the browser from the Open PR in browser menu item, in both ladders", async () => { + for (const build of CLEAN_LADDERS) { + testState.openPullRequestLink.mockClear(); + testState.openPullRequest.mockClear(); + testState.statusQuery.data = build({ pr: OPEN_MR }); + render(buildProps()); + menuItemByText("Open PR in browser")?.onClick?.(); + await flushPromises(); + expect(testState.openPullRequestLink).toHaveBeenCalledWith( + (testState.localApi as { shell: unknown }).shell, + OPEN_MR.url, + ); + expect(testState.openPullRequest).not.toHaveBeenCalled(); + } + }); + + it("opens View PR in the browser when the server cannot read pull requests", async () => { + testState.pullRequestsReads = false; + for (const build of CLEAN_LADDERS) { + testState.openPullRequestLink.mockClear(); + testState.statusQuery.data = build({ pr: OPEN_MR }); + render(buildProps()); + expect(menuItemByText("Open PR in browser")).toBeUndefined(); + (buttonsByText("View PR")[0] ?? menuItemByText("View PR"))?.onClick?.(); + await flushPromises(); + expect(testState.openPullRequestLink).toHaveBeenCalledTimes(1); + expect(testState.openPullRequest).not.toHaveBeenCalled(); + } + }); + it("opens the open merge request in the thread's panel from the legacy menu", () => { testState.statusQuery.data = legacyStatus({ sourceControlProvider: { kind: "gitlab", name: "GitLab", baseUrl: "https://gitlab.test" }, @@ -855,7 +916,7 @@ describe("SourceControlPanel", () => { }); const props = buildProps(); render(props); - menuItemByText("Open MR in panel")?.onClick?.(); + menuItemByText("View MR")?.onClick?.(); expect(testState.openPullRequest).toHaveBeenCalledWith(props.threadRef, { number: 89, provider: "gitlab", @@ -1933,7 +1994,8 @@ describe("SourceControlPanel", () => { expect(testState.runAction.mock.calls[0]?.[0]).not.toHaveProperty("commitStagedIndexAsIs"); }); - it("opens an existing PR from the legacy quick action", async () => { + it("opens an existing PR from the legacy quick action in the browser without pull request reads", async () => { + testState.pullRequestsReads = false; testState.statusQuery.data = legacyStatus({ hasWorkingTreeChanges: false, workingTree: { files: [], insertions: 0, deletions: 0 }, diff --git a/apps/web/src/components/SourceControlPrimaryAction.logic.test.ts b/apps/web/src/components/SourceControlPrimaryAction.logic.test.ts index 2e28480b2..0978a573e 100644 --- a/apps/web/src/components/SourceControlPrimaryAction.logic.test.ts +++ b/apps/web/src/components/SourceControlPrimaryAction.logic.test.ts @@ -219,12 +219,36 @@ describe("resolveSourceControlPrimaryAction — commit-first ladder", () => { hasPrimaryRemote: false, }), ); - assert.deepEqual(action, { kind: "open_pr", label: "View PR", disabled: false }); + assert.deepEqual(action, { kind: "open_pr_panel", label: "View PR", disabled: false }); }); - it("views an open PR when clean, synced, and a PR is open", () => { + it("views an open PR in the panel when clean, synced, and a PR is open", () => { const action = resolveSourceControlPrimaryAction(makeInput({ status: { pr: OPEN_PR } })); - assert.deepEqual(action, { kind: "open_pr", label: "View PR", disabled: false }); + assert.deepEqual(action, { kind: "open_pr_panel", label: "View PR", disabled: false }); + }); + + it("views an open PR in the browser when the panel cannot show it", () => { + for (const statusOverrides of [ + { pr: OPEN_PR }, + { hasUpstream: false, aheadCount: 0, pr: OPEN_PR }, + ]) { + const action = resolveSourceControlPrimaryAction( + makeInput({ status: statusOverrides, hasPrimaryRemote: false, canOpenInPanel: false }), + ); + assert.deepEqual(action, { kind: "open_pr", label: "View PR", disabled: false }); + } + }); + + it("words the panel action View MR on GitLab", () => { + const action = resolveSourceControlPrimaryAction( + makeInput({ + status: { + pr: OPEN_PR, + sourceControlProvider: { kind: "gitlab", name: "GitLab", baseUrl: "https://gitlab.test" }, + }, + }), + ); + assert.deepEqual(action, { kind: "open_pr_panel", label: "View MR", disabled: false }); }); it("creates a PR when synced with upstream but ahead of the default ref", () => { @@ -408,20 +432,20 @@ describe("buildSourceControlMenuItems — always-rendered, disabled-with-reason" "push", "pull", "merge", - "open_pr", "open_pr_panel", + "open_pr", ]); - assert.deepInclude(menuItem(items, "open_pr"), { - label: "View PR", - disabled: false, - kind: "open_pr", - }); assert.deepInclude(menuItem(items, "open_pr_panel"), { - label: "Open PR in panel", + label: "View PR", disabled: false, kind: "open_pr_panel", group: "remote", }); + assert.deepInclude(menuItem(items, "open_pr"), { + label: "Open PR in browser", + disabled: false, + kind: "open_pr", + }); }); it("omits the in-panel action where the panel cannot show the request", () => { @@ -429,7 +453,7 @@ describe("buildSourceControlMenuItems — always-rendered, disabled-with-reason" makeInput({ status: { aheadCount: 2, pr: OPEN_PR }, canOpenInPanel: false }), ); assert.notInclude(menuIds(items), "open_pr_panel"); - assert.include(menuIds(items), "open_pr"); + assert.deepInclude(menuItem(items, "open_pr"), { label: "View PR", kind: "open_pr" }); }); it("offers no in-panel action without an open request", () => { From 41f53b8eac64f35fcb47addbc901d3c8025cf9c4 Mon Sep 17 00:00:00 2001 From: mubeda <1380447+mubeda@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:00:35 -0300 Subject: [PATCH 003/242] fix(web): open View PR in the PR panel and keep a browser menu item View PR (View MR on GitLab) called openPullRequestLink, so the browser opened even where the panel can show the request. Both action ladders now return open_pr_panel when the setting is on, the host has request details and the server reports pullRequestsReads. Without that, View PR still opens the browser. The menu item formerly named "Open PR in panel" is now the View PR item, and "Open PR in browser" opens the URL. Co-Authored-By: Claude Fable 5.2 --- .../GitActionsControl.logic.test.ts | 11 +++++---- .../src/components/GitActionsControl.logic.ts | 20 +++++++++------- .../web/src/components/SourceControlPanel.tsx | 24 ++++++++++++------- .../SourceControlPrimaryAction.logic.ts | 18 +++++++------- 4 files changed, 43 insertions(+), 30 deletions(-) diff --git a/apps/web/src/components/GitActionsControl.logic.test.ts b/apps/web/src/components/GitActionsControl.logic.test.ts index 8341aebdb..2b57e9b1e 100644 --- a/apps/web/src/components/GitActionsControl.logic.test.ts +++ b/apps/web/src/components/GitActionsControl.logic.test.ts @@ -168,7 +168,7 @@ describe("when: ref is clean and has an open PR", () => { ); }); - it("buildMenuItems disables opening the PR in the panel while busy", () => { + it("buildMenuItems disables both PR items while busy", () => { const withPr = status({ pr: { number: 11, @@ -179,10 +179,11 @@ describe("when: ref is clean and has an open PR", () => { state: "open", }, }); - assert.deepInclude(buildMenuItems(withPr, true, true, true).at(-1), { - id: "pr_panel", - disabled: true, - }); + const prItems = buildMenuItems(withPr, true, true, true).filter((item) => item.icon === "pr"); + assert.deepEqual( + prItems.map((item) => item.disabled), + [true, true], + ); }); it("buildMenuItems disables commit/push and enables open PR", () => { diff --git a/apps/web/src/components/GitActionsControl.logic.ts b/apps/web/src/components/GitActionsControl.logic.ts index ce82f7ab9..149555206 100644 --- a/apps/web/src/components/GitActionsControl.logic.ts +++ b/apps/web/src/components/GitActionsControl.logic.ts @@ -17,7 +17,7 @@ export type GitActionIconName = "commit" | "push" | "pr"; export type GitDialogAction = "commit" | "push" | "create_pr"; export interface GitActionMenuItem { - id: "commit" | "push" | "pr" | "pr_panel"; + id: "commit" | "push" | "pr" | "pr_browser"; label: string; disabled: boolean; icon: GitActionIconName; @@ -28,7 +28,7 @@ export interface GitActionMenuItem { export interface GitQuickAction { label: string; disabled: boolean; - kind: "run_action" | "run_pull" | "open_pr" | "open_publish" | "show_hint"; + kind: "run_action" | "run_pull" | "open_pr" | "open_pr_panel" | "open_publish" | "show_hint"; action?: GitStackedAction; hint?: string; } @@ -154,7 +154,7 @@ export function buildMenuItems( label: `View ${terminology.shortLabel}`, disabled: !canOpenPr, icon: "pr", - kind: "open_pr", + kind: canOpenInPanel ? "open_pr_panel" : "open_pr", } : { id: "pr", @@ -167,11 +167,11 @@ export function buildMenuItems( ]; if (canOpenInPanel && hasOpenPr) { items.push({ - id: "pr_panel", - label: `Open ${terminology.shortLabel} in panel`, + id: "pr_browser", + label: `Open ${terminology.shortLabel} in browser`, disabled: !canOpenPr, icon: "pr", - kind: "open_pr_panel", + kind: "open_pr", }); } return items; @@ -182,6 +182,7 @@ export function resolveQuickAction( isBusy: boolean, isDefaultRef = false, hasPrimaryRemote = true, + canOpenInPanel = false, ): GitQuickAction { if (isBusy) { return { label: "Commit", disabled: true, kind: "show_hint", hint: "Git action in progress." }; @@ -204,6 +205,7 @@ export function resolveQuickAction( const isBehind = gitStatus.behindCount > 0; const isDiverged = isAhead && isBehind; const terminology = resolveChangeRequestTerminology(gitStatus); + const viewKind = canOpenInPanel ? "open_pr_panel" : "open_pr"; if (!hasBranch) { return { @@ -232,7 +234,7 @@ export function resolveQuickAction( if (!gitStatus.hasUpstream) { if (!hasPrimaryRemote) { if (hasOpenPr && !isAhead) { - return { label: `View ${terminology.shortLabel}`, disabled: false, kind: "open_pr" }; + return { label: `View ${terminology.shortLabel}`, disabled: false, kind: viewKind }; } return { label: "Publish repository", @@ -242,7 +244,7 @@ export function resolveQuickAction( } if (!isAhead) { if (hasOpenPr) { - return { label: `View ${terminology.shortLabel}`, disabled: false, kind: "open_pr" }; + return { label: `View ${terminology.shortLabel}`, disabled: false, kind: viewKind }; } return { label: "Push", @@ -302,7 +304,7 @@ export function resolveQuickAction( } if (hasOpenPr && gitStatus.hasUpstream) { - return { label: `View ${terminology.shortLabel}`, disabled: false, kind: "open_pr" }; + return { label: `View ${terminology.shortLabel}`, disabled: false, kind: viewKind }; } if (hasDefaultBranchDelta && !isDefaultRef) { diff --git a/apps/web/src/components/SourceControlPanel.tsx b/apps/web/src/components/SourceControlPanel.tsx index 82e828857..80ed63a3a 100644 --- a/apps/web/src/components/SourceControlPanel.tsx +++ b/apps/web/src/components/SourceControlPanel.tsx @@ -421,17 +421,21 @@ export default function SourceControlPanel({ [codeReviewMenuReviewers, codeReviewScope, status], ); + // The panel can show the request only on a host that has it, with the setting on and a server + // that reads pull requests. Otherwise View PR opens the browser. + const canOpenInPanel = + capabilities?.pullRequestsReads === true && + canOpenPullRequestInPanel({ + enabled: pullRequestsEnabled, + providerKind: status?.sourceControlProvider?.kind ?? "unknown", + }); // Legacy servers (no staging areas) keep the chat-header cascade // (commit_push-first, commit-by-filePaths). The primary button and dropdown // below fork on `hasAreas`: this pair drives the legacy branch unchanged. const quickAction = useMemo( - () => resolveQuickAction(status, isBusy, isDefaultRef, hasPrimaryRemote), - [status, isBusy, isDefaultRef, hasPrimaryRemote], + () => resolveQuickAction(status, isBusy, isDefaultRef, hasPrimaryRemote, canOpenInPanel), + [status, isBusy, isDefaultRef, hasPrimaryRemote, canOpenInPanel], ); - const canOpenInPanel = canOpenPullRequestInPanel({ - enabled: pullRequestsEnabled, - providerKind: status?.sourceControlProvider?.kind ?? "unknown", - }); const menuItems = useMemo( () => buildMenuItems(status, isBusy, hasPrimaryRemote, canOpenInPanel), [status, isBusy, hasPrimaryRemote, canOpenInPanel], @@ -1036,12 +1040,13 @@ export default function SourceControlPanel({ const onPrimaryAction = useCallback(() => { if (quickAction.kind === "open_pr") return openPr(); + if (quickAction.kind === "open_pr_panel") return openPrInPanel(); if (quickAction.kind === "run_pull") return void runPull(); if (quickAction.kind === "run_action" && quickAction.action) { return void runGitAction(quickAction.action); } // open_publish / show_hint: no-op here (surfaced as disabled below). - }, [openPr, quickAction, runGitAction, runPull]); + }, [openPr, openPrInPanel, quickAction, runGitAction, runPull]); // Commit-first ladder dispatch (staging-area servers). Commit-family actions // route through runGitAction, which holds the ledger guard (commit the staged @@ -1063,9 +1068,12 @@ export default function SourceControlPanel({ case "open_pr": openPr(); return; + case "open_pr_panel": + openPrInPanel(); + return; // publish / sync_hint / none: disabled below, no-op here. } - }, [primaryAction, runGitAction, runStage, runPull, openPr, groups]); + }, [primaryAction, runGitAction, runStage, runPull, openPr, openPrInPanel, groups]); const onScMenuItem = useCallback( (item: SourceControlMenuItem) => { diff --git a/apps/web/src/components/SourceControlPrimaryAction.logic.ts b/apps/web/src/components/SourceControlPrimaryAction.logic.ts index 10ee4dc02..2a88cfa8c 100644 --- a/apps/web/src/components/SourceControlPrimaryAction.logic.ts +++ b/apps/web/src/components/SourceControlPrimaryAction.logic.ts @@ -34,6 +34,7 @@ export type SourceControlPrimaryActionKind = | "publish" | "create_pr" | "open_pr" + | "open_pr_panel" | "none"; export interface SourceControlPrimaryAction { @@ -96,7 +97,7 @@ export interface SourceControlPrimaryActionInput { stageableCount: number; /** The environment runs Git Manager fetch and merge operations for this project. */ mergeAvailable: boolean; - /** The thread's right panel can show this branch's request (setting on, host supported). */ + /** The thread's right panel can show this branch's request (setting on, host and server support it). */ canOpenInPanel: boolean; } @@ -151,6 +152,7 @@ function resolvePrimaryActionForStatus( const terminology = resolveChangeRequestTerminology(gitStatus); const changeRequestsEnabled = supportsChangeRequests(gitStatus); const pushEnabledForRef = canPushFromCurrentRef(gitStatus); + const viewPrKind = input.canOpenInPanel ? "open_pr_panel" : "open_pr"; // Staged content always wins — commit the staged index as-is. Enabled even // with an empty message (auto-generate divergence); ordering intentionally @@ -196,7 +198,7 @@ function resolvePrimaryActionForStatus( if (!gitStatus.hasUpstream) { if (!hasPrimaryRemote) { if (changeRequestsEnabled && hasOpenPr && !isAhead) { - return { kind: "open_pr", label: `View ${terminology.shortLabel}`, disabled: false }; + return { kind: viewPrKind, label: `View ${terminology.shortLabel}`, disabled: false }; } return { kind: "publish", label: "Publish repository", disabled: false }; } @@ -265,7 +267,7 @@ function resolvePrimaryActionForStatus( } if (changeRequestsEnabled && hasOpenPr) { - return { kind: "open_pr", label: `View ${terminology.shortLabel}`, disabled: false }; + return { kind: viewPrKind, label: `View ${terminology.shortLabel}`, disabled: false }; } if (changeRequestsEnabled && pushEnabledForRef && hasDefaultBranchDelta && !isDefaultRef) { @@ -386,10 +388,10 @@ export function buildSourceControlMenuItems( }, changeRequestsEnabled && hasOpenPr ? { - id: "open_pr", + id: input.canOpenInPanel ? "open_pr_panel" : "open_pr", label: `View ${terminology.shortLabel}`, group: "remote", - kind: "open_pr", + kind: input.canOpenInPanel ? "open_pr_panel" : "open_pr", ...gate(undefined), } : changeRequestsEnabled @@ -417,10 +419,10 @@ export function buildSourceControlMenuItems( : null, changeRequestsEnabled && hasOpenPr && input.canOpenInPanel ? { - id: "open_pr_panel", - label: `Open ${terminology.shortLabel} in panel`, + id: "open_pr", + label: `Open ${terminology.shortLabel} in browser`, group: "remote", - kind: "open_pr_panel", + kind: "open_pr", ...gate(undefined), } : null, From 7d1c049e4169cddb77964532f960cc494cc3f573 Mon Sep 17 00:00:00 2001 From: mubeda <1380447+mubeda@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:00:59 -0300 Subject: [PATCH 004/242] test(web): pin the server's guard names in the branch dialogs and dropdown The server emits checkout, delete-branch and rename-branch. These cases mix unrelated reasons into each branch so a lookup by the wrong name, or a fallback to the first reason, fails. They fail before the fix (#401). Co-Authored-By: Claude Opus 5.5 --- .../dialogs/GitManagerBranchDialogs.test.tsx | 113 +++++++++++++++++- .../toolbar/GitManagerBranchDropdown.test.tsx | 110 ++++++++++++++++- 2 files changed, 219 insertions(+), 4 deletions(-) diff --git a/apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.test.tsx b/apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.test.tsx index 83b566731..2be1f65c4 100644 --- a/apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.test.tsx +++ b/apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.test.tsx @@ -159,7 +159,7 @@ describe("GitManagerBranchDialogs", () => { dialog={{ kind: "rename", branch: branch("feature", { - blocked: [{ operation: "branch-rename", code: "worktree-checked-out", message }], + blocked: [{ operation: "rename-branch", code: "worktree-checked-out", message }], }), }} errorMessage={null} @@ -319,6 +319,117 @@ describe("GitManagerBranchDialogs", () => { expect(submissions).toEqual([{ kind: "delete", name: "old-feature", deleteRemote: false }]); }); + + async function renderBranchDialog( + dialog: React.ComponentProps["dialog"], + ) { + const submissions: GitManagerBranchDialogSubmission[] = []; + await act(async () => + root?.render( + undefined} + onSubmit={(submission) => { + submissions.push(submission); + return Promise.resolve(); + }} + />, + ), + ); + return submissions; + } + + async function confirmDelete() { + const confirmation = document.querySelector('input[name="confirm-delete"]'); + if (!confirmation) throw new Error("Missing delete confirmation"); + await act(async () => confirmation.click()); + } + + const MERGE_DIRTY = { + operation: "merge", + code: "dirty-working-tree", + message: "Merge is blocked: the working tree has uncommitted changes.", + } as const; + + it("shows the server's delete reason among unrelated ones and sends nothing", async () => { + const message = "Delete is blocked: this is the default branch."; + const submissions = await renderBranchDialog({ + kind: "delete", + branch: branch("main", { + blocked: [MERGE_DIRTY, { operation: "delete-branch", code: "default-branch", message }], + }), + existsUpstream: false, + }); + + await confirmDelete(); + const deleteButton = buttonWithText("Delete branch"); + expect(document.body.textContent).toContain(message); + expect(document.body.textContent).not.toContain(MERGE_DIRTY.message); + expect(deleteButton.disabled).toBe(true); + await act(async () => deleteButton.click()); + expect(submissions).toEqual([]); + }); + + it("blocks delete while an operation holds the repository", async () => { + const message = "Blocked: a merge is in progress; resolve or abort it first."; + await renderBranchDialog({ + kind: "delete", + branch: branch("feature", { + // The server emits both spellings for in-progress and lock-held reasons. + blocked: [ + { operation: "branch-delete", code: "merge-in-progress", message }, + { operation: "delete-branch", code: "merge-in-progress", message }, + ], + }), + existsUpstream: false, + }); + + await confirmDelete(); + expect(buttonWithText("Delete branch").disabled).toBe(true); + expect(document.body.textContent).toContain(message); + }); + + it("deletes and renames a branch that is blocked only for merge", async () => { + const blocked = [MERGE_DIRTY]; + const deletions = await renderBranchDialog({ + kind: "delete", + branch: branch("feature", { blocked }), + existsUpstream: false, + }); + await confirmDelete(); + await act(async () => buttonWithText("Delete branch").click()); + expect(deletions).toEqual([{ kind: "delete", name: "feature", deleteRemote: false }]); + + const renames = await renderBranchDialog({ + kind: "rename", + branch: branch("feature", { blocked }), + }); + expect(document.body.textContent).not.toContain(MERGE_DIRTY.message); + const input = document.querySelector('input[aria-label="New branch name"]'); + await setInputValue(input!, "feature-two"); + await act(async () => buttonWithText("Rename").click()); + expect(renames).toEqual([{ kind: "rename", name: "feature", newName: "feature-two" }]); + }); + + it("shows the server's rename reason and not an unrelated one", async () => { + const message = "Rename is blocked: the worktree at /opaque/feature has this branch checked out."; + await renderBranchDialog({ + kind: "rename", + branch: branch("feature", { + blocked: [MERGE_DIRTY, { operation: "rename-branch", code: "worktree-checked-out", message }], + }), + }); + + const input = document.querySelector('input[aria-label="New branch name"]'); + await setInputValue(input!, "feature-two"); + expect(document.body.textContent).toContain(message); + expect(document.body.textContent).not.toContain(MERGE_DIRTY.message); + expect(buttonWithText("Rename").disabled).toBe(true); + }); }); describe("GitManagerSwitchWithChangesDialog", () => { diff --git a/apps/web/src/components/gitManager/toolbar/GitManagerBranchDropdown.test.tsx b/apps/web/src/components/gitManager/toolbar/GitManagerBranchDropdown.test.tsx index 85b99174b..ef4677ea5 100644 --- a/apps/web/src/components/gitManager/toolbar/GitManagerBranchDropdown.test.tsx +++ b/apps/web/src/components/gitManager/toolbar/GitManagerBranchDropdown.test.tsx @@ -181,7 +181,7 @@ describe("GitManagerBranchDropdown", () => { const callbacks = await renderDropdown([ branch("feature", { worktreePath: "/opaque/feature", - blocked: [{ operation: "branch-checkout", code: "worktree-checked-out", message }], + blocked: [{ operation: "checkout", code: "worktree-checked-out", message }], }), ]); expect(document.body.textContent).toContain("Switch to worktree"); @@ -198,7 +198,7 @@ describe("GitManagerBranchDropdown", () => { await renderDropdown([ branch("main", { current: true, - blocked: [{ operation: "branch-checkout", code: "current-branch", message }], + blocked: [{ operation: "checkout", code: "current-branch", message }], }), ]); @@ -218,7 +218,7 @@ describe("GitManagerBranchDropdown", () => { branch("future", { blocked: [ { - operation: "branch-checkout", + operation: "checkout", code: "future-policy" as never, message, }, @@ -296,4 +296,108 @@ describe("GitManagerBranchDropdown", () => { await act(async () => rowButton("Choose a branch to merge into main").click()); expect(container.textContent).not.toContain("Remote branches"); }); + + const dirty = (operation: string, label: string) => ({ + operation, + code: "dirty-working-tree" as const, + message: `${label} is blocked: the working tree has uncommitted changes.`, + }); + + it("lets a dirty checkout through to the Stash or Bring choice", async () => { + const callbacks = await renderDropdown([ + branch("feature", { + blocked: [dirty("checkout", "Checkout"), dirty("merge", "Merge"), dirty("rebase", "Rebase")], + }), + ]); + + expect(rowButton("feature").disabled).toBe(false); + await act(async () => rowButton("feature").click()); + expect(callbacks.onSelectBranch).toHaveBeenCalledWith( + expect.objectContaining({ name: "feature" }), + false, + ); + }); + + it("does not stop checkout for a merge, rebase or push reason", async () => { + const callbacks = await renderDropdown([ + branch("feature", { + blocked: [ + dirty("merge", "Merge"), + dirty("rebase", "Rebase"), + { + operation: "push", + code: "no-upstream", + message: "Push is blocked: this branch has no upstream.", + }, + ], + }), + ]); + + expect(rowButton("feature").disabled).toBe(false); + expect(document.body.textContent).not.toContain("Merge is blocked"); + await act(async () => rowButton("feature").click()); + expect(callbacks.onSelectBranch).toHaveBeenCalledTimes(1); + }); + + it("shows a real checkout block ahead of unrelated reasons", async () => { + const message = "Blocked: another Git Manager operation is already running."; + const callbacks = await renderDropdown([ + branch("feature", { + blocked: [ + dirty("merge", "Merge"), + { operation: "checkout", code: "operation-in-flight", message }, + ], + }), + ]); + + const row = rowButton("feature"); + expect(row).toMatchObject({ disabled: true, title: message }); + expect(document.getElementById(row.getAttribute("aria-describedby")!)?.textContent).toBe( + message, + ); + await act(async () => row.click()); + expect(callbacks.onSelectBranch).not.toHaveBeenCalled(); + }); + + it("still redirects a worktree-held branch whose checkout is also dirty", async () => { + const callbacks = await renderDropdown([ + branch("held", { + worktreePath: "/opaque/held", + blocked: [ + dirty("checkout", "Checkout"), + { + operation: "checkout", + code: "worktree-checked-out", + message: "Checkout is blocked: this branch is already checked out in the worktree.", + }, + ], + }), + ]); + + await act(async () => rowButton("held").click()); + expect(callbacks.onSwitchWorktree).toHaveBeenCalledWith("/opaque/held"); + expect(callbacks.onSelectBranch).not.toHaveBeenCalled(); + }); + + it("in merge mode, blocks a branch with the merge reason only", async () => { + const merge = dirty("merge", "Merge"); + const callbacks = await renderDropdown([ + branch("main", { current: true }), + branch("feature", { blocked: [dirty("checkout", "Checkout"), merge] }), + branch("clean", { + blocked: [ + { + operation: "push", + code: "no-upstream", + message: "Push is blocked: this branch has no upstream.", + }, + ], + }), + ]); + + await act(async () => rowButton("Choose a branch to merge into main").click()); + expect(rowButton("feature")).toMatchObject({ disabled: true, title: merge.message }); + await act(async () => rowButton("clean").click()); + expect(callbacks.onMergeInto).toHaveBeenCalledWith(expect.objectContaining({ name: "clean" })); + }); }); From 5dd6ab53cc1fe9c42a58e0e06e929cde27e5103a Mon Sep 17 00:00:00 2001 From: mubeda <1380447+mubeda@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:01:53 -0300 Subject: [PATCH 005/242] fix(web): read the server's guard names in the branch dialogs and dropdown The dialogs looked up branch-delete and branch-rename, and the dropdown exempted a dirty reason only for branch-checkout, while the server emits delete-branch, rename-branch and checkout. Any other reason, such as a merge or push reason, also blocked rename and checkout through a first-reason fallback. Each action now reads its own reason from one module of server names, so a dirty checkout reaches Stash or Bring and merge mode reads the merge reason. Closes #401 Co-Authored-By: Claude Opus 5.5 --- .../dialogs/GitManagerBranchDialogs.tsx | 8 +++---- .../gitManager/gitManagerGuardOperations.ts | 9 ++++++++ .../toolbar/GitManagerBranchDropdown.tsx | 23 ++++++++++--------- 3 files changed, 25 insertions(+), 15 deletions(-) create mode 100644 apps/web/src/components/gitManager/gitManagerGuardOperations.ts diff --git a/apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.tsx b/apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.tsx index 2e0cb0f25..d17202171 100644 --- a/apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.tsx +++ b/apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.tsx @@ -24,6 +24,7 @@ import { } from "~/components/ui/dialog"; import { Input } from "~/components/ui/input"; import { GitManagerDisabledReasonButton } from "../GitManagerDisabledReasonButton"; +import { GUARD_DELETE_BRANCH, GUARD_RENAME_BRANCH } from "../gitManagerGuardOperations"; export type GitManagerBranchDialog = | { @@ -313,9 +314,7 @@ function RenameBranchDialog({ const [name, setName] = useState(branch.name); const trimmedName = name.trim(); const serverBlock = - branch.blocked.find((reason) => reason.operation === "branch-rename") ?? - branch.blocked[0] ?? - null; + branch.blocked.find((reason) => reason.operation === GUARD_RENAME_BRANCH) ?? null; const duplicate = refs.some( (ref) => ref.name !== branch.name && ref.name.toLocaleLowerCase() === trimmedName.toLocaleLowerCase(), @@ -396,7 +395,8 @@ function DeleteBranchDialog({ }) { const [confirmed, setConfirmed] = useState(false); const [deleteRemote, setDeleteRemote] = useState(false); - const serverBlock = branch.blocked.find((reason) => reason.operation === "branch-delete") ?? null; + const serverBlock = + branch.blocked.find((reason) => reason.operation === GUARD_DELETE_BRANCH) ?? null; const disabledReason = capabilityDisabledReason ?? serverBlock?.message ?? null; const submit = useCallback(() => { if (!confirmed || disabledReason !== null) return; diff --git a/apps/web/src/components/gitManager/gitManagerGuardOperations.ts b/apps/web/src/components/gitManager/gitManagerGuardOperations.ts new file mode 100644 index 000000000..0165a119e --- /dev/null +++ b/apps/web/src/components/gitManager/gitManagerGuardOperations.ts @@ -0,0 +1,9 @@ +/** + * Operation names the server's guards emit in `GitManagerBlockedReason.operation` + * (`apps/server/src/git/manager/guards.rs`). They differ from the request tags + * (`branch-delete`, `branch-checkout`), which name what the client sends. + */ +export const GUARD_DELETE_BRANCH = "delete-branch"; +export const GUARD_RENAME_BRANCH = "rename-branch"; +export const GUARD_CHECKOUT = "checkout"; +export const GUARD_MERGE = "merge"; diff --git a/apps/web/src/components/gitManager/toolbar/GitManagerBranchDropdown.tsx b/apps/web/src/components/gitManager/toolbar/GitManagerBranchDropdown.tsx index 1a0d29e18..87b056983 100644 --- a/apps/web/src/components/gitManager/toolbar/GitManagerBranchDropdown.tsx +++ b/apps/web/src/components/gitManager/toolbar/GitManagerBranchDropdown.tsx @@ -24,6 +24,7 @@ import { } from "react"; import { GitManagerDisabledReasonButton } from "../GitManagerDisabledReasonButton"; +import { GUARD_CHECKOUT, GUARD_MERGE } from "../gitManagerGuardOperations"; import { Input } from "~/components/ui/input"; import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover"; import { cn } from "~/lib/utils"; @@ -143,12 +144,16 @@ const GitManagerBranchRow = memo(function GitManagerBranchRow({ ? refEntry.worktreePath : null; const unknownReason = refEntry.blocked.find((reason) => !KNOWN_BLOCKED_CODES.has(reason.code)); - const checkoutBlock = refEntry.blocked.find( - (reason) => - redirectPath === null && - !(reason.operation === "branch-checkout" && reason.code === "dirty-working-tree"), - ); - const blockedReason = unknownReason ?? checkoutBlock ?? null; + // Each row action reads its own reason. A dirty checkout is not blocked: the toolbar + // offers Stash or Bring for it. + const actionBlock = mergeMode + ? refEntry.blocked.find((reason) => reason.operation === GUARD_MERGE) + : redirectPath === null + ? refEntry.blocked.find( + (reason) => reason.operation === GUARD_CHECKOUT && reason.code !== "dirty-working-tree", + ) + : undefined; + const blockedReason = unknownReason ?? actionBlock ?? null; const capabilityDisabledReason = mergeMode ? mergeDisabledReason : redirectPath === null @@ -157,11 +162,7 @@ const GitManagerBranchRow = memo(function GitManagerBranchRow({ const currentMergeReason = mergeMode && refEntry.current ? "Choose a different branch to merge." : null; const displayReason = - capabilityDisabledReason ?? - blockedReason?.message ?? - currentMergeReason ?? - refEntry.blocked[0]?.message ?? - null; + capabilityDisabledReason ?? blockedReason?.message ?? currentMergeReason ?? null; const descriptionId = displayReason === null ? undefined From 9baf86244f7237cfb4e10036becdaa49c8264f95 Mon Sep 17 00:00:00 2001 From: mubeda <1380447+mubeda@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:06:07 -0300 Subject: [PATCH 006/242] docs(plans): design Antigravity terminal and ACP chat provider The owner decided on 2026-11-20 that the chat over agy acp lands in the same pull request as the terminal, so the note designs both modes and records what changes if the chat is dropped again. It classifies every registration site, picks the 1.5.4 version gate, reuses the Cursor ACP transport, and proposes the chat task breakdown. Review record pending. Refs #399 Co-Authored-By: Claude Opus 5.5 --- .../2026-11-20-antigravity-terminal-design.md | 438 ++++++++++++++++++ 1 file changed, 438 insertions(+) create mode 100644 docs/plans/2026-11-20-antigravity-terminal-design.md diff --git a/docs/plans/2026-11-20-antigravity-terminal-design.md b/docs/plans/2026-11-20-antigravity-terminal-design.md new file mode 100644 index 000000000..6bd4cca89 --- /dev/null +++ b/docs/plans/2026-11-20-antigravity-terminal-design.md @@ -0,0 +1,438 @@ +# Antigravity terminal and chat: design (issue 399) + +Status: draft for review. It becomes approved when the Codex and advisor +reviews in the "Review record" section are handled (spec D6). + +Scope. Issue 399 asks for an Antigravity AI Terminal that starts the `agy` TUI. +On 2026-11-20 the owner decided that the same pull request also builds an +Antigravity chat panel over `agy acp` (ACP v1, JSON-RPC over stdio), with no +SDK. That reverses spec R13 and D9. This note designs both modes. The +"Terminal only" section at the end lists what changes if the chat were dropped +again, so either answer stays possible. + +Sources. The research report `research-antigravity.md` in +`docs/plans/2026-11-20-undo-remote-delete-antigravity/` (CLI 1.5.13, read on +2026-11-20, nothing installed or run) and the source at commit `56573c19e`. +No `agy` binary was installed or run for this note, and none exists in CI or +the labs. + +## External facts this note relies on + +Each fact was read on 2026-11-20 through a summarizing fetch, not by running +the CLI. + +| Fact | Source | Status | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------- | ------------------------ | +| `--model` selects the session model (see `agy models`). | CLI reference, command-line flags table | Read | +| `--effort` sets reasoning effort, `low` through `max` depending on the model. | CLI reference | Read | +| `--dangerously-skip-permissions` auto-approves all tool permission requests. | CLI reference | Read | +| `-c` and `--continue` continue the latest conversation; `--conversation` resumes one by id. | CLI reference | Read | +| The reference does not list `--version`. | CLI reference | Read | +| `agy --version` verifies the installation. | Getting started page, CLI tab | Read | +| Plain `agy` launches the interactive TUI in the current directory. | Getting started page, commands table | Read | +| The first launch asks for a colour scheme, Alt-Screen or Inline mode, and workspace trust. | Getting started page | Read | +| `agy acp` is an ACP v1 server over stdio; editors launch command `agy` with args `["acp"]`. | Research report, ACP section | Research, not re-read | +| Flags after `acp` include `--dangerously-skip-permissions`, `--process-per-session` and `--login`. | Research report | Research, not re-read | +| An unauthenticated ACP call fails with JSON-RPC `-32000` "Authentication required". | Research report | Research, not re-read | +| An initialize response from 1.5.9 shows `loadSession: true` and no `authMethods` in the excerpt. | Research report, upstream issue 1604 | Research, not re-read | +| `session/load` replays no history. | Research report, upstream issue 1672 | Research, not re-read | +| Provider failures end `session/prompt` with `stopReason: end_turn` and the error only as message text. | Research report, upstream issue 1570 | Research, not re-read | +| `agy acp` shipped in 1.5.0; a third-party tracker puts session fixes in 1.5.4; Orca gates host ACP at 1.5.2. | Research report and its addendum | Third-party, unconfirmed | +| ACP model and thinking-level options exist; the exact method and option shape are not confirmed from a raw trace. | Issue 399 table, research open questions | Unconfirmed | +| The FAQ says wrapping `agy` in third-party tools is not supported on consumer plans; a forum reply on Google's behalf says the unmodified official ACP server is supported for single-user interactive development. | Research report, terms section | Research, conflicting | + +## Decisions + +Each decision names the alternative that lost and its trade-off. + +### D-A1. Driver slug `antigravity` + +The driver kind is `antigravity`, the default instance id is `antigravity`, +and the label is "Antigravity". + +Lost: `agy`. It is the binary name, and the slug must not be used as the +executable (issue 399). A slug equal to the binary would hide a missing +special case in `default_provider_binary`. The editor catalog's id +`antigravity` (`packages/contracts/src/editor.ts`) is a separate namespace +(`EditorId`) and stays unchanged (R13, third bullet). + +### D-A2. Disabled by default (spec D7) + +`built_in_provider_defaults()` gains +`"antigravity": { "enabled": false, "binaryPath": "agy", "customModels": [] }`, +and `AntigravitySettings.enabled` decodes to `false`. + +The inventory's synthesized roster in `provider_inventory::definitions` falls +back to `unwrap_or(true)` when settings carry no `enabled` value. Settings that +went through `apply_settings_defaults` always carry it, but raw settings (a +test's `json!({})`, `maintenance_target`, `instance_custom_models`) do not. The +roster therefore reads the fallback from `built_in_provider_defaults()`, the one +table both settings readers already use, so `definitions(&json!({}))` yields a +disabled Antigravity instance. A user-created instance under +`providerInstances` without `enabled` keeps the existing `true` default, +because the user added it. + +Lost: enabled but unready, like Cursor. Every machine without `agy` would then +show an error card, and a user who never asked for Antigravity would see it in +pickers once `agy` exists on PATH for another reason (the IDE launcher clash +below). + +Roster order. `antigravity` goes last in the roster loop, the exact-order test +and every built-in list, so it is never the first enabled provider that a +"first enabled" fallback picks before a user has chosen it. + +### D-A3. Binary path and install probe + +The binary path defaults to `agy`, never the slug: `default_provider_binary` +gains `"antigravity" => "agy"`, the settings schema uses +`makeBinaryPathSetting("agy")` with placeholder `agy`, and the legacy patch +validation accepts `providers.antigravity.binaryPath` as a string. The probe is +the existing generic one: ` --version`, run only for an enabled +instance. A binary that cannot be started reads "not installed"; a `--version` +that exits non-zero reads installed with a warning (the existing behaviour at +`provider_inventory.rs` lines 731 to 742). + +Lost: resolving every `agy` on PATH and keeping the one whose output looks like +the CLI (research recommendation). It needs a second probe format that no +source documents. The configured binary path and the documented check +(`agy --version`, and `command -v agy` or `where agy`) cover the clash. + +### D-A4. Version gate for chat: 1.5.4 + +The inventory parses the version line and reports an instance older than +1.5.4 as status `error` with the message "Antigravity CLI is older +than 1.5.4, the first version BiBCode's chat supports. Run `agy update`, then +check again." This follows the OpenCode precedent (`OpenCodeCliSupport:: +Unsupported` sets `status = "error"`). An unparsable version is not gated and +logs one `tracing::warn!` without the output text, so a changed version format +does not lock users out. + +Why 1.5.4. 1.5.0 introduced `agy acp`, 1.5.1 made every model work in ACP +clients, and 1.5.4 added session fixes (third-party tracker). Session load is +how BiBCode resumes a chat after a restart, so the gate follows the session +fixes. The CLI updates itself near daily, so the gate costs little. + +Lost: 1.5.2 (Orca's gate). Orca keeps a managed ACP server as its fallback; +BiBCode has none, so it takes the later, safer version. Lost too: a separate +readiness per mode, so that an old CLI keeps the terminal. That needs a new +`ServerProvider` field. Below 1.5.4 both modes are disabled, with the message +above as the reason. + +### D-A5. Permission flag + +The terminal passes `--dangerously-skip-permissions` (spec D8), the same +default as BiBCode's other terminals and Orca's default. + +The chat does not pass it. The chat answers each `session/request_permission` +from the thread's runtime mode through the shared +`acp_mode::auto_approved_option_id`, as Cursor does: `full-access` approves, +other modes ask the user. A flag on `agy acp` would fix the policy for the +process and ignore a thread switched to approval-required later. + +Lost for the terminal: no flag, so the TUI prompts (the research's first +advice). Lost for the chat: Orca's flag on `agy acp`. Lost for both: a +per-agent permission setting, which no BiBCode terminal has; it would be its +own issue. + +### D-A6. Model and effort + +Catalog. The slow inventory probe starts `agy acp`, sends `initialize` and +`session/new` with the probe directory, and reads the model and thinking-level +options from the response. The parser handles the ACP `configOptions` shape +that `cursor::build_capabilities_from_config_options` already reads, and the +ACP `models` shape. An empty or unknown answer leaves the instance's custom +models, so a parse failure never blocks the chat. A `-32000` answer sets +`auth.status = "unauthenticated"`, status `warning` and the sign-in message +(D-A8). The quick probe stays `--version` only. + +Lost: `agy models`. Its output format is not published, and it gives no sign-in +signal. Cost of the chosen path: each slow probe creates one empty Antigravity +session, as the Cursor probe does with `cursor-agent acp`. + +Chat. A turn's model reaches the session through `session/set_config_option` +(or `session/set_model` if only the `models` shape is advertised). Effort +reaches it through the thinking-level option when the catalog advertises one. +An option the session does not advertise is rejected with the existing +"unsupported option" error. + +Terminal. `--model` and `--effort` come only from the raw +`settings.providerSessionDefaults.antigravity` value: `model`, and the first +option whose id is in `PROVIDER_EFFORT_OPTION_IDS`. The resolver's fallback +never adds them. Two reasons hold even with a catalog: R12 passes the flags +only when session defaults supply them, and the ACP option ids are not +confirmed to equal the CLI's `--model` slugs. Without a configured default, the +TUI starts on its own default model. + +Settings card. The card shows the binary path and the shared session-defaults +control for the default instance. With a catalog, the control offers the +advertised models and, when present, the thinking level. Without one, it +offers custom models only and no effort. + +Lost: a free-text model and effort field on the card. It is new UI with no +validation source. + +### D-A7. Reuse of the Cursor ACP code + +The transport is reused as it is. `provider::cursor::acp` +(`AcpJsonRpcConnection`, line bounds, error classes, `acp_turn_state`) already +serves Grok through a re-export in `provider/grok/mod.rs`. A new +`provider/antigravity/` module re-exports it the same way and adds its own +`runtime.rs`, modeled on `cursor/runtime.rs` for the standard ACP v1 methods: +`initialize`, `session/new`, `session/load`, `session/prompt`, +`session/cancel`, `session/set_mode`, `session/set_config_option`, +`session/request_permission` and `session/update`. It drops the Cursor +extensions (`cursor/ask_question`, `cursor/create_plan`, `cursor/update_todos`) +and `authenticate`, and handles the Antigravity `ask_question` extension only if +its method name is confirmed from a fixture taken from the docs. Otherwise the +request is answered with JSON-RPC "method not found" and logged without content. + +Lost, option 2: move `cursor/acp.rs` to `provider/acp/` first. It is a rename +across Cursor, Grok and the inventory imports with no behaviour change, so it +belongs in its own change. Lost, option 3: generalize `CursorSessionRuntime` +into a dialect (provider name, auth method, extension table). Antigravity's +real wire format is unverified, so coupling the shipped Cursor chat to guesses +about `agy` risks a Cursor regression; a second implementation keeps the risk +in the new driver. If the third ACP runtime turns out close to Cursor's after +real use, the dialect refactor becomes the follow-up. + +### D-A8. Chat launch and authentication + +Launch. The driver spawns ` acp` through `spawn_child`, with the +thread checkout as working directory and the instance's provider environment +(`provider_launch_environment`), like `CursorDriver::spawn`. It adds no flag +(D-A5) and no environment variable. `mcpServers` is sent empty (D-A9). + +Authentication. BiBCode never signs the user in, never reads Google +credentials or keyring entries, and offers no ACP auth method id. It does not +call `authenticate`, because the research reports that `authenticate` can open +a browser even with a valid token (upstream issue 1637). The CLI's cached sign-in +from an interactive `agy` or `agy acp --login` is used. A `-32000` answer to +any request becomes `ProviderRuntimeError::Provider` with the message +"Antigravity is not signed in. Open an Antigravity Terminal and run `agy`, or +run `agy acp --login`, then send the message again." + +Lost: offering `terminal-login` or `oauth-personal` through `authenticate`. Both +start a sign-in BiBCode would have to drive. + +### D-A9. Sessions and resume + +The ACP `sessionId` is the resume token, stored in the turn's resume cursor as +for Cursor (`provider_runtime.rs` `cursor_field` `"sessionId"`). After a server +restart the driver calls `session/load` with the saved id. Because load replays +nothing, BiBCode's own projected transcript stays the record the user sees; the +agent keeps its server-side context. If load fails permanently (not found, or +`-32603` "trajectory not found"), the driver starts `session/new` and posts the +existing "the provider started a new session" notice, so the user knows the +agent lost its context. + +Not supported in the first version: + +- `session/list`, because it can return desktop-app sessions that then fail. +- Forks and conversation rewind: `supports_conversation_rewind` stays false, + and checkpoint rollback returns the existing `unsupported` error. +- Turn steering and compaction. +- MCP passing. `mcpServers` is empty, so BiBCode's MCP tools are not offered to + Antigravity. HTTP MCP servers need `--process-per-session`, whose effect on + session load is unverified. +- Images beyond what the shared attachment path already does. Attachments go + through `AttachmentMaterializer` and `append_file_references` as text file + references, as for Cursor. + +### D-A10. Known ACP bugs and their effect + +- Provider and quota errors end a prompt with `end_turn` and the error only as + text (upstream 1570). The first version shows that text as the reply and + marks the turn completed. Scanning message text for errors is left out, + because the wording is not documented. +- `session/list` returning foreign sessions (D-A9) does not apply, because the + client never calls it. +- A subagent's `run_command` can time out without a permission request + (upstream 1658). In approval-required mode such a command fails inside the + agent; in full-access mode no request is needed. The provider guide states it. +- A session can wedge after `ask_question` plus load (upstream 1581). Cancel + sends `session/cancel`; if the turn does not settle, the existing idle + deadline ends it and the next turn restarts the process. + +### D-A11. Process supervision and Profiler coverage + +- The chat child spawns through `spawn_child`, which applies + `configure_supervised_background_command_wrap` and registers the process with + the `ProcessAttributionRegistry` passed to the driver. An unrequested exit is + reported by the shared `exits::report_exit` path that every driver already + feeds through `exited_child`, so it becomes a `subprocess.crash`. +- The inventory probe spawns through `supervised_command` and + `stop_supervised_child`, as the Cursor probe does. +- No RPC method is added. Chat uses the existing orchestration methods, so + `is_long_running` needs no entry. +- Logs carry the method name, error code and class only, never prompt, + message, option values or terminal content. + +### D-A12. Server dispatch + +`canonical_provider_kind` gains `"antigravity"`; `provider_binary_settings` +reads `providers.antigravity`; `native_adapter_key` returns `antigravity-acp`; +the driver factory gains an `AntigravityDriver`; `cursor_field` treats it as +`sessionId`; the ACP line-too-long classifier includes it; `turn_delivery`'s +outcome table treats an ACP send without a native id as `Uncertain`, like +Cursor. `orchestration_rpc.rs` reaches the driver through +`canonical_provider_kind`, so it needs no edit. + +### D-A13. Display name + +`provider_display_name("antigravity")` returns "Antigravity", and contracts' +`PROVIDER_DISPLAY_NAMES` gains the same entry, so the snapshot's `displayName` +is "Antigravity" and the existing parity test +`provider_display_names_match_the_contracts_table` keeps them equal. + +### D-A14. First-run prompts and the PATH clash + +The TUI's first launch asks for a colour scheme, a rendering mode and +workspace trust inside the embedded terminal. BiBCode does not answer them and +does not write workspace trust (Orca does; BiBCode never edits Antigravity's +settings files). The chat is not affected by those prompts, which belong to the +TUI. The provider guide states that the first terminal run per workspace is +interactive. + +The IDE once shipped a launcher also named `agy`; newer IDE releases are +reported to install `agy-ide` and `antigravity-ide`. If an old launcher is +first on PATH, both the terminal and the chat run the wrong program. The +`--version` probe then fails or prints a non-CLI line, so the card shows an +error. The fix is an absolute binary path in Settings, and the guide shows how +to check which `agy` is found. + +### D-A15. Google's terms + +The research reports that Google's FAQ says third-party tools wrapping `agy` +are not supported on consumer plans, while a forum reply written on Google's +behalf says the unmodified official ACP server is supported for single-user +interactive development. Whether a distributed desktop app counts is not +established. The terminal runs the user's own unmodified CLI interactively. +The chat runs the unmodified official `agy acp` with the user's own sign-in, +and never proxies tokens, rotates accounts or wraps `agy -p`. The provider +guide must say that the position is unresolved, link the terms and the FAQ, +and name an API key or an enterprise plan as the officially supported route. +The research's advice to get a written answer from Google before shipping chat +publicly is an open decision for the owner. + +## Registration sites + +Command, from the repository root at commit `56573c19e`: + +```bash +rg -n '"cursor"|cursor-agent|CursorSettings|CURSOR_DRIVER_KIND|make\("cursor"\)|"grok"' packages apps/web/src apps/web/visual apps/server/src apps/server/tests -g '!**/provider/cursor/**' -g '!**/provider/grok/**' +``` + +It prints 844 lines in 154 files. Every file is in exactly one row below. +Classes: "registration" (needs an `antigravity` entry for the instance, Task +3.2), "chat" (needs an entry when the chat lands, later tasks), "terminal" +(needs an entry for the terminal, Task 3.4), "unrelated" (no entry; the reason +says why). Review finding 8 of plan review 1 is covered by the rows marked +"(R1-8)". + +| File (lines) | Class | Action or reason | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `packages/contracts/src/settings.ts` (425 to 470, 657, 762, 819) | registration | `AntigravitySettings`, the `providers.antigravity` key, `AntigravitySettingsPatch` and its patch key. | +| `packages/contracts/src/model.ts` (133, 134, 219) | registration | Driver constant and `PROVIDER_DISPLAY_NAMES` entry (R1-8). Lines 148, 159 and 195 (default model, text-generation model, aliases) get no entry: the CLI picks its own default. | +| `packages/contracts/fixtures/rpc-wire/stream-shapes/subscribeServerConfig-00.json`, `packages/contracts/fixtures/rpc-wire/stream-shapes/subscribeServerConfig-03.json` | registration | Regenerated by `vp run check:contracts` when the settings shape gains the key. | +| `apps/server/src/server_settings/mod.rs` (18, 19, 76, 77, 488, 490, 640, 641, 743 to 764) | registration | Built-in default, `ProvidersState` field, `ProvidersPatch` field and its `apply_provider_patch` call with fallback `agy`, test table (R1-8). | +| `apps/server/src/production/control.rs` (2824, 2825) | registration | `validate_legacy_provider_settings` accepts `antigravity` with string `binaryPath` (R1-8). The other 62 hits are tests of Cursor and Grok behaviour: unrelated. Line 3719's test pins legacy providers; Antigravity is disabled by default, so it is never probed there. | +| `apps/server/src/production/provider_inventory.rs` (182, 186, 187, 278, 2062, 2921, 2924) | registration | `default_provider_binary`, roster loop with the built-in enabled fallback (D-A2), `is_builtin_driver`, exact-order test (R1-8). Lines 470, 484, 778, 916, 953, 998, 1020 are chat (D-A4, D-A6: version gate, ACP probe, models). The other hits are Cursor and Grok tests: unrelated. | +| `apps/server/src/production/provider_runtime.rs` (2539, 2540, 23016) | registration | `provider_display_name` and its parity test (R1-8). Lines 6813, 6979, 6980, 6995, 6996, 13632, 13633, 14779, 14787, 21441 are chat (D-A12). Line 7023 and 9735 are the Grok chat refusal: unrelated. The other hits are Cursor and Grok driver code and tests: unrelated. | +| `apps/server/src/hermetic_guard.rs` (17, 19, 394) | registration | `GUARDED_PROGRAMS` gains `agy`; the tripwire list at 394 gains `agy` (R14). | +| `apps/server/tests/support/hermetic_providers.rs` (4, 29, 70, 71) | registration | `BUILTIN_PROVIDER_DRIVERS` and the enabled table gain `("antigravity", false)` (R1-8). | +| `apps/server/src/test_support/mod.rs` (159, 160, 237, 254, 274, 290) | registration | The parity test's typed-field table gains `providers.antigravity` (R1-8). | +| `apps/server/tests/cli_smoke.rs` (52) | registration | Optional: the pinned-binary loop could include `antigravity`. Not owned by Task 3.2; the parity test already covers the hermetic table. | +| `apps/web/src/components/chat/providerTerminalActions.ts` (51, 52, 55, 56, 140, 150) | terminal | `DEFINITIONS` entry and argv from the raw settings value (D-A6). Lines 140 and 150 are Cursor and Grok argv. Code review terminals (`REVIEW_ARGUMENTS`) get no entry: no read-only flag is verified. | +| `apps/web/src/components/settings/providerDriverMeta.ts` (4, 51, 54, 57) | terminal | Driver definition with `AntigravityIcon` and `AntigravitySettings`. | +| `apps/web/src/components/chat/providerIconUtils.ts` (9, 10) | terminal | Icon map entry. | +| `apps/web/src/session-logic.ts` (39, 40) | terminal | `PROVIDER_OPTIONS` entry, which feeds the icon list `AVAILABLE_PROVIDER_OPTIONS`. | +| `apps/web/src/components/settings/SettingsPanels.tsx` (1675, 1791) | unrelated | Grok exclusions; Antigravity is shown like other providers. | +| `apps/web/src/components/chat/ChatHeaderPanelMenu.logic.ts` (58) | unrelated | Grok exclusion from the panel menu. With chat built, Antigravity is not excluded. | +| `apps/web/src/components/chat/ChatComposer.tsx` (921) | chat | Native skill invocation; Antigravity gets `slash` only if its ACP session advertises slash commands. Otherwise unchanged. | +| `apps/web/src/lib/contextWindow.ts` (41) | unrelated | Context-window labels for drivers that report usage; Antigravity reports none. | +| `apps/web/src/composerDraftStore.ts` (839, 998, 2879) | unrelated | Migration of a legacy per-provider draft shape that predates Antigravity. | +| `apps/web/src/components/settings/ProviderModelsSection.tsx` (36) | unrelated | Custom-model placeholder; the generic placeholder serves. | +| `apps/web/src/components/chat/OpenInPicker.tsx` (70), `packages/contracts/src/editor.ts` (16), `packages/contracts/src/editor.test.ts`, `apps/server/src/production/editor_launch.rs` (53), `apps/web/src/editorPreferences.test.ts`, `apps/web/src/editorPreferences.hooks.test.tsx`, `apps/web/src/localApi.test.ts`, `apps/web/src/components/chat/OpenInPicker.test.tsx`, `apps/web/src/components/Sidebar.test.tsx` | unrelated | The editor catalog ("Open in Cursor"); "Open in Antigravity" stays unchanged. | +| `packages/contracts/src/mcpClients.ts` (11), `apps/server/src/production/mcp_client_registration/mod.rs`, `apps/server/src/production/mcp_client_registration/tests.rs`, `apps/web/src/components/settings/AgentIntegrationsSection.test.tsx` | unrelated | MCP client registration writes BiBCode into an agent's own config; BiBCode never edits Antigravity's config files. | +| `apps/server/src/production/provider_maintenance.rs`, `apps/server/src/production/provider_maintenance/source.rs`, `apps/server/src/production/provider_maintenance/latest.rs`, `apps/server/tests/fixtures/cursor_update_fixture.rs`, `apps/web/src/components/ProviderUpdateLaunchNotification.logic.test.ts`, `apps/web/src/hooks/useAgentFreshness.card.test.tsx` | unrelated | Cursor's update source. `provider_version_scheme("antigravity")` is `None`, so no latest version and no update action is offered. `source.rs` line 596 sends it to `resolve_package_managed_capabilities`, which only reads paths; an open question asks whether to add it to the Grok `unknown()` arm. | +| `apps/server/src/production/provider_inventory/capabilities.rs` (27) | unrelated | Cursor's skill discovery; Antigravity's skills are not discovered in the first version. | +| `apps/server/src/production/turn_delivery.rs` (1998, 2439, 3698) | chat | Line 1998: ACP send outcome (D-A12). The test lines are Cursor's. | +| `apps/server/src/production/runtime.rs` (3730, 3731, 4607), `apps/server/tests/server_runtime.rs`, `apps/server/tests/remote_update_rpc.rs`, `apps/server/tests/production_control.rs`, `apps/server/tests/server_settings_domain.rs`, `apps/server/tests/turn_delivery_recovery.rs`, `apps/server/tests/provider_terminal_supervisor.rs`, `apps/server/tests/production_provider_runtime.rs`, `apps/server/tests/provider_codex.rs`, `apps/server/src/production/shared_checkout_restore_tests.rs`, `apps/server/src/production/thread_compaction_tests.rs`, `apps/server/src/persistence/repositories.rs`, `apps/server/src/send_requests/terminal/tests.rs`, `apps/server/src/agent_messaging/directory.rs`, `apps/server/src/agent_messaging/envelope.rs` | unrelated | Tests that name Cursor or Grok as sample drivers or disable them in fixtures. Antigravity is disabled by default, so no fixture probes it. Chat tasks add their own tests instead of extending these. | +| `apps/server/src/webhooks/events.rs`, `apps/server/src/webhooks/tests.rs`, `apps/server/src/mcp/thread_cli.rs`, `apps/server/src/mcp/thread_cli/tests.rs`, `apps/server/src/mcp/tools/feed.rs`, `apps/server/src/mcp/tools/git.rs`, `apps/server/src/mcp/tools/pull_requests.rs`, `apps/server/src/mcp/tools/terminals.rs`, `apps/server/src/mcp/tools/threads.rs`, `apps/server/src/mcp/tools/worktrees.rs`, `apps/server/src/diagnostics/profiler/mcp.rs`, `apps/server/src/workspace/rpc.rs`, `apps/server/src/production/orchestration_rpc.rs`, `apps/server/src/production/orchestration_rpc/thread_history.rs`, `apps/server/src/production/pipelines_rpc.rs`, `apps/server/src/production/git_vcs.rs`, `apps/server/src/production/mcp_tools_tests/diagnostics.rs`, `apps/server/src/production/mcp_tools_tests/feed.rs`, `apps/server/src/production/mcp_tools_tests/git_reads.rs`, `apps/server/src/production/mcp_tools_tests/panels.rs`, `apps/server/src/production/mcp_tools_tests/pull_requests.rs`, `apps/server/src/production/mcp_tools_tests/terminals.rs`, `apps/server/src/production/mcp_tools_tests/threads.rs`, `apps/server/src/production/mcp_tools_tests/worktrees.rs`, `apps/server/src/pull_requests/mod.rs`, `apps/server/src/pull_requests/github/files.rs`, `apps/server/src/pull_requests/github/mod.rs`, `apps/server/src/pull_requests/github/runs.rs`, `apps/server/src/pull_requests/github/timeline.rs`, `apps/server/src/pull_requests/gitlab/mod.rs`, `apps/server/src/pull_requests/gitlab/pipelines.rs`, `apps/server/src/pull_requests/gitlab/timeline.rs`, `apps/server/src/pull_requests/pipelines/model.rs`, `apps/server/src/provider/codex/model.rs`, `apps/server/src/provider/codex/runtime.rs`, `apps/server/src/provider/opencode/runtime.rs`, `apps/server/src/provider/opencode/v2_runtime_tests.rs`, `apps/server/src/provider/opencode/quiet/test_server.rs`, `apps/server/tests/activity_load.rs`, `apps/server/tests/activity_rpc.rs`, `apps/server/tests/production_git_vcs_rpc.rs`, `apps/server/tests/production_orchestration_rpc.rs`, `apps/server/tests/pull_requests_context_list.rs`, `apps/server/tests/pull_requests_gitlab_load_harness.rs`, the ten `apps/server/tests/fixtures/opencode-v2/*.exchanges.json` files, `packages/contracts/fixtures/thread-stream/window.json` | unrelated | The word `cursor` as a pagination cursor, a JSON key or a mock agent name. | +| `apps/web/src/components/ui/sidebar.tsx`, `apps/web/src/components/ui/sidebar.rail.test.tsx`, `apps/web/src/hooks/useResizableWidth.ts`, `apps/web/src/hooks/useResizableWidth.test.ts`, `apps/web/src/components/terminalTheme.ts`, `packages/contracts/src/theme.ts`, `apps/web/src/themes/builtin/matrix-dark.json`, `apps/web/src/themes/builtin/matrix-light.json`, `apps/web/src/themes/builtin/tokyo-night.json`, `apps/web/src/themes/builtin/verdant-light.json`, `apps/web/src/themes/builtinThemes.test.ts`, `apps/web/src/connection/storage.test.ts`, `apps/web/src/components/chat/ChatComposer.rerender.test.tsx`, `packages/contracts/src/terminal.test.ts` | unrelated | The CSS or terminal cursor, an IndexedDB cursor, a theme colour, or a sample path. | +| `apps/web/src/components/chat/providerTerminalActions.test.ts`, `apps/web/src/components/chat/providerAgentActions.test.ts`, `apps/web/src/components/chat/ChatHeaderPanelMenu.logic.test.ts`, `apps/web/src/components/settings/SettingsPanels.test.tsx`, `apps/web/src/components/chat/ModelPickerContent.test.tsx`, `apps/web/src/components/chat/modelPickerSearch.test.ts`, `apps/web/src/components/chat/ChatComposer.test.tsx`, `apps/web/src/components/chat/RevertCheckpointDialog.logic.test.ts`, `apps/web/src/components/ChatView.test.tsx`, `apps/web/src/components/ChatView.hooks.test.tsx`, `apps/web/src/components/ChatView.logic.test.ts`, `apps/web/src/components/CreateWorktreeDialog.test.tsx`, `apps/web/src/components/CreateWorktreeDialog.settings.dom.test.tsx`, `apps/web/src/components/ThreadTerminalPanel.interactions.test.tsx`, `apps/web/src/components/sendToAgent/sendToAgent.logic.test.ts`, `apps/web/src/components/sendToAgent/outOfTokens.logic.test.ts`, `apps/web/src/components/sidebar/agentsSection.agents.test.ts`, `apps/web/src/agentStatus.server.test.tsx`, `apps/web/src/centerPanelActions.test.ts`, `apps/web/src/codeReview.test.ts`, `apps/web/src/modelSelection.test.ts`, `apps/web/src/composerDraftStore.test.ts`, `apps/web/src/lib/contextWindow.test.ts`, `packages/contracts/src/settings.test.ts`, `packages/contracts/src/provider.test.ts`, `packages/shared/src/model.test.ts`, `packages/shared/src/providerSessionDefaults.test.ts` | unrelated | Existing tests of Cursor and Grok behaviour. New Antigravity tests go beside them in the tasks that change the code; `settings.test.ts` and `providerTerminalActions.test.ts` are the natural homes. | + +Sites the command does not find, found by reading the callers: + +- Chat choosers that pick the first enabled provider: `resolveThreadProviderBinding`, + `resolveSelectableProvider`, `resolveSelectableProviderInstance`, + `resolveAppModelSelectionState` (text generation), `Sidebar.tsx` line 2397, + `WorktreeDiscoverySection.tsx` line 84, and the composer model picker. With + chat built, Antigravity is a valid chat target, so they need no change. Roster + order (D-A2) keeps it from being the first fallback. +- `provider::supports_turn_steer`, `supports_conversation_rewind` and + `supports_compaction` return false for an unknown driver, which is the + intended first-version answer. + +## Terminal only, if the chat were dropped + +If the owner reverses the chat decision, these change and nothing else: +D-A4 has no version gate; D-A6 has no catalog and no ACP probe; D-A7 to D-A12 +fall away; the server refuses a chat start for the driver before +`canonical_provider_kind` (in `resolve_provider_route_settings` and the second +caller `instance_provider_kind` in `orchestration_rpc.rs`); one exported web +predicate keeps Antigravity out of every chat chooser listed above, including +`Sidebar.tsx` and `WorktreeDiscoverySection.tsx`; and the Settings card says +that chat is not supported yet. Task 3.2 is the same in both answers. + +## Task breakdown proposal + +Task 3.2 (registration) is unchanged and lands first. The chat tasks follow. + +| Task | Files | Red-first tests | Done when | Depends on | +| ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | ---------- | +| C1. ACP session runtime | create `apps/server/src/provider/antigravity/{mod.rs,runtime.rs}`; modify `apps/server/src/provider/mod.rs` | A fixture ACP server over in-memory pipes, like `grok/runtime.rs` tests: `initialize` then `session/new` with cwd and empty `mcpServers`, and no `authenticate`; `-32000` maps to the sign-in message; load of a saved id, and fallback to new on a permanent failure; permission answered by runtime mode; `session/cancel`; chunks before the prompt response belong to the turn. | `cargo test -p bibcode-server antigravity` | 3.2 | +| C2. Runtime dispatch | modify `apps/server/src/production/provider_runtime.rs`, `apps/server/src/production/turn_delivery.rs` | A chat start for the default and a custom `antigravity` instance spawns ` acp` (fixture executable) with the checkout as cwd; `native_adapter_key`; resume cursor field; delivery outcome; display label in errors. | `cargo test -p bibcode-server provider_runtime` | C1 | +| C3. Inventory version gate, auth, models | modify `apps/server/src/production/provider_inventory.rs` | 1.5.3 reads `error` with the update message and 1.5.4 reads ready; unparsable version is not gated; the ACP probe fixture yields models and thinking levels; a `-32000` probe reads unauthenticated with the sign-in message; disabled instance not probed. | `cargo test -p bibcode-server provider_inventory` | 3.2 | +| C4. Web terminal and chat enablement | modify `providerTerminalActions.ts`, `providerDriverMeta.ts`, `providerIconUtils.ts`, `session-logic.ts`, and their tests | Terminal argv cases of Task 3.4 step 1; the menu lists Antigravity chat and terminal for a ready instance; the Settings card has binary path `agy` and the session-defaults control; one production-shaped inventory-to-menu-to-terminal-open test. | `cd apps/web && node ../../scripts/run-local-vp.mjs test run --project unit src/components/chat src/components/settings` | 3.2, C3 | +| C5. Provider guide | create `docs/providers/antigravity.md`; modify `docs/providers/README.md`, `docs/architecture/providers.md`, `docs/README.md` | None (documentation). | `vp run check:markdown-links` and `vp check` | C1 to C4 | + +C1 and C3 can run in parallel after 3.2. C2 needs C1. C4 needs C3's snapshot +shape. The hermetic guard already blocks `agy` after 3.2, so no task can start +the real CLI. + +## Size and risk judgment + +Size. C1 is the large task: the Cursor runtime it is modeled on is 1,463 lines +with tests, and the Grok runtime 884. C2 adds a driver of about 150 lines, +following `GrokDriver`. C3 adds a probe of about 80 lines, following +`probe_cursor_models`. The whole chat is about the size of the Grok driver, +which this repository built and then kept disabled for chat. + +Risk. Every ACP behaviour in this note is proven only against fixtures written +from documentation and one issue excerpt, because no lane may install or run +`agy`, and none exists in CI or the labs. The method names for model and +thinking-level options, the `ask_question` extension, the `-32000` shape and +the session-load failure text are unconfirmed. ACP in `agy` is about 16 days +old with open bugs that hide errors (D-A10). The terms question (D-A15) is open. + +Judgment. The chat is buildable in this pull request, but it cannot be +verified end to end here. I recommend that it ship behind the disabled default +(D-A2) with a badge such as "Preview" on the Settings card, and that the pull +request say plainly that no live `agy acp` session was run. If the owner wants +a verified chat, a run against a real `agy` on a developer machine is the one +check this plan cannot automate. + +## Open questions for the owner + +1. Ship the chat with a "Preview" badge and no live verification, or hold it + until someone runs it against a real `agy`? +2. Ask Google for a written answer on a distributed desktop host before the + chat ships publicly (research recommendation)? +3. Add `antigravity` to the Grok `unknown()` arm in + `provider_maintenance/source.rs`, so BiBCode never infers a package-managed + update for `agy`, which updates itself? + +## Review record + +Pending: Codex read-only review and advisor review. From 43e6c2d805418a607745c003097519c5eca2fbcf Mon Sep 17 00:00:00 2001 From: mubeda <1380447+mubeda@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:08:05 -0300 Subject: [PATCH 007/242] test(desktop): add a packaged spec that measures Files undo and redo per path Issue #398 reports that only the toolbar moves the Files history. The spec seeds one fresh edit per case and sends the chord through the WebDriver driver, and, when BIBCODE_E2E_NATIVE_INPUT=1 is set in a lab, as a real operating-system keystroke and through the native Edit menu. It records what reached the page for the diagnosis matrix. Co-Authored-By: Claude Fable 5.2 --- .../e2e/specs/files-undo-shortcuts.e2e.ts | 537 ++++++++++++++++++ apps/desktop/e2e/wdio.conf.ts | 1 + 2 files changed, 538 insertions(+) create mode 100644 apps/desktop/e2e/specs/files-undo-shortcuts.e2e.ts diff --git a/apps/desktop/e2e/specs/files-undo-shortcuts.e2e.ts b/apps/desktop/e2e/specs/files-undo-shortcuts.e2e.ts new file mode 100644 index 000000000..966ba6196 --- /dev/null +++ b/apps/desktop/e2e/specs/files-undo-shortcuts.e2e.ts @@ -0,0 +1,537 @@ +// @effect-diagnostics nodeBuiltinImport:off - Packaged UI tests write fixture files, record evidence and send native input. +// @effect-diagnostics globalTimers:off - The spec waits out the editors' history grouping delay. +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; + +import { desktopUiApplicationPid, desktopUiPlatform } from "../support/app-lifecycle.ts"; +import { desktopUiFixture } from "../support/test-project.ts"; +import { + ensureMainSidebarOpen, + mockDesktopUiFolderPicker, + setDesktopUiWindowSize, +} from "../support/ui-state.ts"; + +const projectPath = process.env.BIBCODE_E2E_PROJECT_PATH; +const artifactDirectory = process.env.BIBCODE_E2E_ARTIFACT_DIR; +if (!projectPath || !artifactDirectory) { + throw new Error("The packaged desktop Files undo fixture environment was not prepared."); +} +const preparedProjectPath: string = projectPath; +const evidencePath = NodePath.join(artifactDirectory, "files-undo-matrix.jsonl"); +const platform = desktopUiPlatform(); +// Native input types into whatever session is in front, so only a lab run turns it on. +const nativeInput = process.env.BIBCODE_E2E_NATIVE_INPUT === "1"; +const bundleIdentifier = "com.bibcode.desktop.e2e"; + +const fileViewSelector = "[data-preview-panel-mode]"; +const richEditorSelector = `${fileViewSelector} .rich-markdown-editor [contenteditable="true"]`; +const sourceHostSelector = `${fileViewSelector} diffs-container`; +const composerSelector = '[data-testid="composer-editor"]'; + +type View = "source" | "rendered"; +type Direction = "undo" | "redo"; +type InputPath = "driver" | "keystroke" | "menu"; +type Chord = "primary+z" | "primary+shift+z" | "ctrl+y"; + +interface ProbeEvent { + readonly type: string; + readonly key: string | null; + readonly inputType: string | null; + readonly cancelable: boolean; + readonly isTrusted: boolean; + readonly defaultPrevented: boolean; + readonly target: string; +} + +interface EditorState { + readonly text: string; + readonly canUndo: boolean; + readonly canRedo: boolean; +} + +declare global { + interface Window { + __bibcodeUndoProbe?: ProbeEvent[]; + } +} + +function recordEvidence(entry: Record): void { + NodeFS.appendFileSync(evidencePath, `${JSON.stringify({ platform, ...entry })}\n`); +} + +async function openFixtureWorkspace(): Promise { + await ensureMainSidebarOpen(); + const project = browser.$( + `//button[.//span[normalize-space()="${desktopUiFixture.projectName}"]]`, + ); + if (!(await project.isDisplayed())) { + const projectDataLoading = browser.$("//*[normalize-space()='Project data is still loading']"); + if (await projectDataLoading.isExisting()) { + await projectDataLoading.waitForDisplayed({ reverse: true }); + } + const addProject = browser.$('[data-testid="sidebar-add-project-trigger"]'); + await addProject.waitForDisplayed(); + await addProject.click(); + const browseFolder = browser.$( + "//button[@data-add-project-action='true'][.//span[normalize-space()='Browse folder']]", + ); + await browseFolder.waitForDisplayed(); + await mockDesktopUiFolderPicker(preparedProjectPath); + await browseFolder.click(); + } + await project.waitForDisplayed(); + const primaryWorkspace = browser.$( + '//*[@data-thread-item="true"][.//span[normalize-space()="main"]]', + ); + if ((await project.getAttribute("aria-expanded")) !== "true") { + await project.click(); + } + await primaryWorkspace.waitForDisplayed(); + await primaryWorkspace.click(); +} + +async function openFilesSurface(): Promise { + const rightPanel = browser.$("[data-right-panel-tabbar]"); + if (!(await rightPanel.isDisplayed())) { + const toggle = browser.$('button[aria-label^="Toggle right panel"]'); + await toggle.waitForDisplayed(); + await toggle.click(); + await rightPanel.waitForDisplayed(); + } + const existingTab = browser.$( + '//*[@data-right-panel-tab-list]//button[normalize-space()="Files"]', + ); + if (await existingTab.isDisplayed()) { + await existingTab.click(); + return; + } + const emptyStateAction = browser.$( + '//button[.//span[normalize-space()="Files"] and not(@aria-disabled="true")]', + ); + if (await emptyStateAction.isDisplayed()) { + await emptyStateAction.click(); + return; + } + const addSurface = browser.$('button[aria-label="Add panel surface"]'); + await addSurface.waitForDisplayed(); + await addSurface.click(); + const menuItem = browser.$('//*[@role="menuitem" and normalize-space()="Files"]'); + await menuItem.waitForDisplayed(); + await menuItem.click(); +} + +/** Writes a fresh file for one case and opens it editable in `view`. */ +async function openFreshFile(view: View, name: string): Promise { + const fileName = view === "source" ? `${name}.txt` : `${name}.md`; + NodeFS.writeFileSync(NodePath.join(preparedProjectPath, fileName), "Hello world\n"); + await setDesktopUiWindowSize(1_200, 720); + await openFixtureWorkspace(); + await openFilesSurface(); + const itemSelector = `[role="treeitem"][data-item-path="${fileName}"]`; + await browser.waitUntil( + () => + browser.execute( + (hostQuery: string, targetQuery: string) => { + const host = [...document.querySelectorAll(hostQuery)].find( + (candidate) => candidate.getBoundingClientRect().height > 0, + ); + const target = host?.shadowRoot?.querySelector(targetQuery); + if (!target) return false; + target.click(); + return true; + }, + `${fileViewSelector} file-tree-container`, + itemSelector, + ), + { timeoutMsg: `The Files tree did not list ${fileName}.` }, + ); + await browser.waitUntil(async () => (await readState(view, fileName)).text.includes("Hello"), { + timeoutMsg: `${fileName} did not open editable in the ${view} view.`, + }); + return fileName; +} + +async function readState(view: View, fileName: string): Promise { + return browser.execute( + (sourceView: boolean, hostQuery: string, richQuery: string, label: string) => { + let text = ""; + if (sourceView) { + const host = [...document.querySelectorAll(hostQuery)].find( + (candidate) => candidate.getBoundingClientRect().height > 0, + ); + text = + host?.shadowRoot?.querySelector(`[role="textbox"][aria-label="${label}"]`)?.textContent ?? + ""; + } else { + text = document.querySelector(richQuery)?.textContent ?? ""; + } + const enabled = (name: string) => { + const button = document.querySelector( + `[data-file-editor-toolbar] button[aria-label="${name}"]`, + ); + return ( + button !== null && !button.disabled && button.getAttribute("aria-disabled") !== "true" + ); + }; + return { text, canUndo: enabled("Undo"), canRedo: enabled("Redo") }; + }, + view === "source", + sourceHostSelector, + richEditorSelector, + fileName, + ); +} + +/** Focuses the editing host and puts the caret at the end of its text. */ +async function placeCaretAtEnd(view: View, fileName: string): Promise { + const placed = await browser.execute( + (sourceView: boolean, hostQuery: string, richQuery: string, label: string) => { + let editor: HTMLElement | null = null; + if (sourceView) { + const host = [...document.querySelectorAll(hostQuery)].find( + (candidate) => candidate.getBoundingClientRect().height > 0, + ); + editor = + host?.shadowRoot?.querySelector(`[role="textbox"][aria-label="${label}"]`) ?? + null; + } else { + editor = document.querySelector(richQuery); + } + if (!editor) return false; + editor.focus(); + const walker = document.createTreeWalker(editor, NodeFilter.SHOW_TEXT); + let last: Text | null = null; + for (let node = walker.nextNode(); node; node = walker.nextNode()) { + if ((node.textContent ?? "").trim().length > 0) last = node as Text; + } + if (!last) return false; + window.getSelection()?.setBaseAndExtent(last, last.length, last, last.length); + return true; + }, + view === "source", + sourceHostSelector, + richEditorSelector, + fileName, + ); + if (!placed) throw new Error(`Could not place the caret in the ${view} view of ${fileName}.`); + // Pierre reads the caret on the next selectionchange. + await new Promise((resolve) => setTimeout(resolve, 200)); +} + +/** Types `marker` through the page: a `beforeinput` the source editor handles, or WebDriver text. */ +async function seedThroughPage(view: View, fileName: string, marker: string): Promise { + await placeCaretAtEnd(view, fileName); + if (view === "rendered") { + await browser.$(richEditorSelector).addValue(marker); + return; + } + await browser.execute( + (hostQuery: string, label: string, data: string) => { + const host = [...document.querySelectorAll(hostQuery)].find( + (candidate) => candidate.getBoundingClientRect().height > 0, + ); + const editor = host?.shadowRoot?.querySelector( + `[role="textbox"][aria-label="${label}"]`, + ); + editor?.dispatchEvent( + new InputEvent("beforeinput", { + inputType: "insertText", + data, + bubbles: true, + cancelable: true, + composed: true, + }), + ); + }, + sourceHostSelector, + fileName, + marker, + ); +} + +function runNative(command: string, args: readonly string[]): string { + return NodeChildProcess.execFileSync(command, args, { encoding: "utf8" }).trim(); +} + +function macSystemEvents(lines: readonly string[]): string { + return runNative("osascript", [ + "-e", + [ + `tell application id "${bundleIdentifier}" to activate`, + 'tell application "System Events"', + ...lines.map((line) => ` ${line}`), + "end tell", + ].join("\n"), + ]); +} + +function powershell(script: string): string { + return runNative("powershell", ["-NoProfile", "-NonInteractive", "-Command", script]); +} + +/** Types plain letters as real operating-system key events. */ +function typeNative(letters: string): void { + if (platform === "mac") macSystemEvents([`keystroke "${letters}"`]); + else if (platform === "win") { + powershell( + `Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.SendKeys]::SendWait('${letters}')`, + ); + } else runNative("xdotool", ["type", "--delay", "40", letters]); +} + +function sendNativeChord(chord: Chord): void { + if (platform === "mac") { + const using = + chord === "primary+z" + ? "{command down}" + : chord === "primary+shift+z" + ? "{command down, shift down}" + : "{control down}"; + macSystemEvents([`keystroke "${chord === "ctrl+y" ? "y" : "z"}" using ${using}`]); + } else if (platform === "win") { + const keys = chord === "primary+z" ? "^z" : chord === "primary+shift+z" ? "^+z" : "^y"; + powershell( + `Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.SendKeys]::SendWait('${keys}')`, + ); + } else { + const keys = + chord === "primary+z" ? "ctrl+z" : chord === "primary+shift+z" ? "ctrl+shift+z" : "ctrl+y"; + runNative("xdotool", ["key", "--clearmodifiers", keys]); + } +} + +/** Chooses Edit > Undo or Redo in the native menu bar. Returns whether the item existed and was enabled. */ +function chooseNativeEditItem(item: "Undo" | "Redo"): { exists: boolean; enabled: boolean } { + if (platform === "mac") { + const reply = macSystemEvents([ + `tell (first application process whose bundle identifier is "${bundleIdentifier}")`, + " set frontmost to true", + ` set target to menu item "${item}" of menu 1 of menu bar item "Edit" of menu bar 1`, + " set isEnabled to enabled of target", + " if isEnabled then click target", + " return isEnabled as text", + " end tell", + ]); + return { exists: true, enabled: reply === "true" }; + } + if (platform === "win") { + const pid = desktopUiApplicationPid(); + const reply = powershell( + [ + "Add-Type -AssemblyName UIAutomationClient, UIAutomationTypes", + "$A = [System.Windows.Automation.AutomationElement]", + "$S = [System.Windows.Automation.TreeScope]::Descendants", + `$window = $A::FromHandle((Get-Process -Id ${pid}).MainWindowHandle)`, + '$named = { param($root, $name) $root.FindAll($S, [System.Windows.Automation.Condition]::TrueCondition) | Where-Object { $_.Current.Name -like "$name*" -and $_.Current.ControlType -eq [System.Windows.Automation.ControlType]::MenuItem } | Select-Object -First 1 }', + "$edit = & $named $window 'Edit'", + "if (-not $edit) { 'missing-edit'; exit }", + "$edit.GetCurrentPattern([System.Windows.Automation.ExpandCollapsePattern]::Pattern).Expand()", + "Start-Sleep -Milliseconds 400", + `$entry = & $named $A::RootElement '${item}'`, + "if (-not $entry) { 'missing-item'; exit }", + "if (-not $entry.Current.IsEnabled) { 'disabled'; exit }", + "$entry.GetCurrentPattern([System.Windows.Automation.InvokePattern]::Pattern).Invoke()", + "'invoked'", + ].join("; "), + ); + return { exists: !reply.startsWith("missing"), enabled: reply === "invoked" }; + } + // The pinned menu library creates no predefined Undo or Redo item on GTK. + return { exists: false, enabled: false }; +} + +async function startProbe(): Promise { + await browser.execute(() => { + const events: ProbeEvent[] = []; + window.__bibcodeUndoProbe = events; + const label = (event: Event) => { + const target = event.composedPath()[0]; + return target instanceof Element + ? `${target.tagName.toLowerCase()}${target.getAttribute("role") ? `[role=${target.getAttribute("role")}]` : ""}` + : String(target); + }; + for (const type of ["keydown", "beforeinput"]) { + window.addEventListener(type, (event) => { + events.push({ + type, + key: event instanceof KeyboardEvent ? event.key : null, + inputType: event instanceof InputEvent ? event.inputType : null, + cancelable: event.cancelable, + isTrusted: event.isTrusted, + defaultPrevented: event.defaultPrevented, + target: label(event), + }); + }); + } + }); +} + +async function readProbe(): Promise { + return browser.execute(() => window.__bibcodeUndoProbe ?? []); +} + +async function sendChord(path: InputPath, chord: Chord, direction: Direction) { + if (path === "keystroke") { + sendNativeChord(chord); + return { menu: null }; + } + if (path === "menu") { + return { menu: chooseNativeEditItem(direction === "undo" ? "Undo" : "Redo") }; + } + const primary = platform === "mac" ? "Meta" : "Control"; + const keys = + chord === "primary+z" + ? [primary, "z"] + : chord === "primary+shift+z" + ? [primary, "Shift", "z"] + : ["Control", "y"]; + await browser.keys(keys); + return { menu: null }; +} + +async function clickToolbar(label: "Undo" | "Redo"): Promise { + const button = await browser.$(`[data-file-editor-toolbar] button[aria-label="${label}"]`); + await button.waitForEnabled(); + await button.click(); +} + +interface Cell { + readonly view: View; + readonly direction: Direction; + readonly path: InputPath; + readonly chord: Chord; +} + +function cellName({ view, direction, path, chord }: Cell): string { + return `${view}-${direction}-${path}-${chord.replaceAll("+", "-")}`; +} + +/** + * Seeds one fresh edit, sends the chord or menu item, and checks that the history moved one step: + * the marker leaves on undo and returns on redo, and the toolbar agrees. + */ +async function measureCell(cell: Cell): Promise { + const name = `undo-${cellName(cell)}`; + const marker = cell.view === "source" ? "kq" : "kqv"; + const fileName = await openFreshFile(cell.view, name); + if (cell.path === "driver") await seedThroughPage(cell.view, fileName, marker); + else { + await placeCaretAtEnd(cell.view, fileName); + typeNative(marker); + } + await browser.waitUntil( + async () => (await readState(cell.view, fileName)).text.includes(marker), + { + timeoutMsg: `The seeded edit "${marker}" never reached ${fileName}.`, + }, + ); + // Past both editors' history grouping delay, so the edit is one closed step. + await new Promise((resolve) => setTimeout(resolve, 800)); + if (cell.direction === "redo") { + await clickToolbar("Undo"); + await browser.waitUntil( + async () => !(await readState(cell.view, fileName)).text.includes(marker), + { timeoutMsg: "The toolbar Undo did not remove the seeded edit." }, + ); + } + const before = await readState(cell.view, fileName); + await startProbe(); + const sent = await sendChord(cell.path, cell.chord, cell.direction); + await new Promise((resolve) => setTimeout(resolve, 800)); + const after = await readState(cell.view, fileName); + const events = await readProbe(); + const expectMarker = cell.direction === "redo"; + const passed = + after.text.includes(marker) === expectMarker && + after.canUndo === expectMarker && + after.canRedo === !expectMarker; + recordEvidence({ cell: cellName(cell), ...cell, passed, before, after, sent, events }); + expect({ + text: after.text.includes(marker), + canUndo: after.canUndo, + canRedo: after.canRedo, + }).toEqual({ text: expectMarker, canUndo: expectMarker, canRedo: !expectMarker }); +} + +const views: readonly View[] = ["source", "rendered"]; +const redoChords: readonly Chord[] = + platform === "mac" ? ["primary+shift+z"] : ["primary+shift+z", "ctrl+y"]; + +describe("packaged Files undo and redo (#398)", () => { + for (const view of views) { + it(`driver: the undo chord undoes one step in the ${view} view`, async () => { + await measureCell({ view, direction: "undo", path: "driver", chord: "primary+z" }); + }); + for (const chord of redoChords) { + it(`driver: ${chord} redoes one step in the ${view} view`, async () => { + await measureCell({ view, direction: "redo", path: "driver", chord }); + }); + } + } + + it("driver: the save chord still saves the source view", async () => { + const fileName = await openFreshFile("source", "undo-save-chord"); + await seedThroughPage("source", fileName, "kq"); + await browser.keys([platform === "mac" ? "Meta" : "Control", "s"]); + await browser.waitUntil( + () => + NodeFS.readFileSync(NodePath.join(preparedProjectPath, fileName), "utf8").includes("kq"), + { timeoutMsg: "The save chord never wrote the edit to disk." }, + ); + }); + + it("driver: the undo chord still undoes in the chat composer", async () => { + await openFixtureWorkspace(); + const composer = browser.$(composerSelector); + await composer.waitForDisplayed(); + await composer.click(); + await composer.addValue("composer undo marker"); + await expect(composer).toHaveText(expect.stringContaining("composer undo marker")); + await new Promise((resolve) => setTimeout(resolve, 800)); + await startProbe(); + await browser.keys([platform === "mac" ? "Meta" : "Control", "z"]); + await new Promise((resolve) => setTimeout(resolve, 500)); + const text = await composer.getText(); + recordEvidence({ cell: "composer-undo-driver", text, events: await readProbe() }); + expect(text).not.toContain("composer undo marker"); + }); + + describe("native input (BIBCODE_E2E_NATIVE_INPUT=1)", function () { + before(function () { + if (!nativeInput) this.skip(); + }); + + for (const path of ["keystroke", "menu"] as const) { + for (const view of views) { + it(`${path}: undo moves the ${view} view one step`, async function () { + if (path === "menu" && platform === "linux") this.skip(); + await measureCell({ view, direction: "undo", path, chord: "primary+z" }); + }); + const chords: readonly Chord[] = path === "menu" ? ["primary+shift+z"] : redoChords; + for (const chord of chords) { + it(`${path}: ${path === "menu" ? "Redo" : chord} redoes the ${view} view one step`, async function () { + if (path === "menu" && platform === "linux") this.skip(); + await measureCell({ view, direction: "redo", path, chord }); + }); + } + } + } + + it("keystroke: the undo chord still undoes in the chat composer", async () => { + await openFixtureWorkspace(); + const composer = browser.$(composerSelector); + await composer.waitForDisplayed(); + await composer.click(); + typeNative("cmpq"); + await expect(composer).toHaveText(expect.stringContaining("cmpq")); + await new Promise((resolve) => setTimeout(resolve, 800)); + await startProbe(); + sendNativeChord("primary+z"); + await new Promise((resolve) => setTimeout(resolve, 500)); + const text = await composer.getText(); + recordEvidence({ cell: "composer-undo-keystroke", text, events: await readProbe() }); + expect(text).not.toContain("cmpq"); + }); + }); +}); diff --git a/apps/desktop/e2e/wdio.conf.ts b/apps/desktop/e2e/wdio.conf.ts index c1ecda2ab..240215f4b 100644 --- a/apps/desktop/e2e/wdio.conf.ts +++ b/apps/desktop/e2e/wdio.conf.ts @@ -69,6 +69,7 @@ const desktopUiSpecFiles = "./specs/mermaid-diagrams.e2e.ts", "./specs/files-binary-preview.e2e.ts", "./specs/files-rich-markdown.e2e.ts", + "./specs/files-undo-shortcuts.e2e.ts", "./specs/appearance-themes.e2e.ts", "./specs/source-control-review.e2e.ts", "./specs/host-dashboard.e2e.ts", From b201c8813935dc2f445a38b79505526a75571dc6 Mon Sep 17 00:00:00 2001 From: mubeda <1380447+mubeda@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:08:26 -0300 Subject: [PATCH 008/242] test(web): pin the View PR fallbacks and the repository check Covers the browser fallback for each unsupported case, the create-PR Done handler without pullRequestsReads, and a pull request that belongs to a repository other than the one the panel addresses. Co-Authored-By: Claude Fable 5.2 --- .../GitActionsControl.logic.test.ts | 45 +++++++ .../components/SourceControlPanel.test.tsx | 114 ++++++++++++++---- 2 files changed, 135 insertions(+), 24 deletions(-) diff --git a/apps/web/src/components/GitActionsControl.logic.test.ts b/apps/web/src/components/GitActionsControl.logic.test.ts index 2b57e9b1e..9a1caeb52 100644 --- a/apps/web/src/components/GitActionsControl.logic.test.ts +++ b/apps/web/src/components/GitActionsControl.logic.test.ts @@ -4,6 +4,8 @@ import { assert, describe, it } from "vite-plus/test"; import { buildGitActionProgressStages, buildMenuItems, + canShowPullRequestInPanel, + isPullRequestInOtherRepository, requiresDefaultBranchConfirmation, resolveAutoFeatureBranchName, resolveDefaultBranchActionDialogCopy, @@ -1277,3 +1279,46 @@ describe("resolveAutoFeatureBranchName", () => { assert.equal(ref, "feature/update"); }); }); + +describe("canShowPullRequestInPanel", () => { + it("needs the setting, a supported host and the server's pullRequestsReads", () => { + const base = { enabled: true, pullRequestsReads: true, providerKind: "github" } as const; + assert.isTrue(canShowPullRequestInPanel(base)); + assert.isFalse(canShowPullRequestInPanel({ ...base, enabled: false })); + assert.isFalse(canShowPullRequestInPanel({ ...base, pullRequestsReads: false })); + assert.isFalse(canShowPullRequestInPanel({ ...base, providerKind: "bitbucket" })); + assert.isFalse(canShowPullRequestInPanel({ ...base, providerKind: "azure-devops" })); + }); +}); + +describe("isPullRequestInOtherRepository", () => { + it("is true only when the pull request URL names a different repository", () => { + assert.isFalse( + isPullRequestInOtherRepository("https://github.test/team/repo/pull/9", "team/repo"), + ); + assert.isFalse( + isPullRequestInOtherRepository("https://github.test/Team/Repo/pull/9", "team/repo"), + ); + assert.isTrue( + isPullRequestInOtherRepository("https://github.test/upstream/repo/pull/9", "fork/repo"), + ); + assert.isFalse( + isPullRequestInOtherRepository( + "https://gitlab.test/group/sub/proj/-/merge_requests/4", + "group/sub/proj", + ), + ); + assert.isTrue( + isPullRequestInOtherRepository( + "https://gitlab.test/group/other/-/merge_requests/4", + "group/sub/proj", + ), + ); + }); + + it("cannot tell, and says false, for an unknown repository or an unrecognised URL", () => { + assert.isFalse(isPullRequestInOtherRepository("https://github.test/team/repo/pull/9", null)); + assert.isFalse(isPullRequestInOtherRepository("not a url", "team/repo")); + assert.isFalse(isPullRequestInOtherRepository("https://host.test/x/y", "team/repo")); + }); +}); diff --git a/apps/web/src/components/SourceControlPanel.test.tsx b/apps/web/src/components/SourceControlPanel.test.tsx index 99c4a5032..2ade1df18 100644 --- a/apps/web/src/components/SourceControlPanel.test.tsx +++ b/apps/web/src/components/SourceControlPanel.test.tsx @@ -136,6 +136,7 @@ const testState = vi.hoisted(() => ({ openPullRequest: vi.fn(), pullRequestsEnabled: true, pullRequestsReads: true, + pullRequestsContext: undefined as { status: string; repository?: string } | undefined, selectGitScope: vi.fn(), toast: { add: vi.fn(), update: vi.fn(), close: vi.fn() }, groupByFolder: true, @@ -425,6 +426,10 @@ vi.mock("~/hooks/useSettings", () => ({ selector({ pullRequestsEnabled: testState.pullRequestsEnabled }), })); +vi.mock("./pullRequests/usePullRequestsContextQuery", () => ({ + usePullRequestsContextQuery: () => ({ query: { data: testState.pullRequestsContext } }), +})); + vi.mock("~/rightPanelStore", () => ({ useRightPanelStore: { getState: () => ({ @@ -781,6 +786,7 @@ beforeEach(() => { testState.openPullRequest.mockReset(); testState.pullRequestsEnabled = true; testState.pullRequestsReads = true; + testState.pullRequestsContext = undefined; testState.selectGitScope.mockReset(); testState.toast.add.mockReset(); testState.toast.add.mockReturnValue("toast-1"); @@ -923,31 +929,89 @@ describe("SourceControlPanel", () => { }); }); + it("opens a GitHub pull request from View PR in the panel, in both ladders", () => { + for (const build of CLEAN_LADDERS) { + testState.openPullRequest.mockClear(); + testState.statusQuery.data = build({ + sourceControlProvider: { kind: "github", name: "GitHub", baseUrl: "https://github.test" }, + pr: { ...OPEN_MR, url: "https://github.test/team/repo/pull/89" }, + }); + const props = buildProps(); + render(props); + (buttonsByText("View PR")[0] ?? menuItemByText("View PR"))?.onClick?.(); + expect(testState.openPullRequest).toHaveBeenCalledWith(props.threadRef, { + number: 89, + provider: "github", + }); + expect(testState.openPullRequestLink).not.toHaveBeenCalled(); + } + }); + it.each([ - ["Pull Requests is turned off", false, "gitlab"], - ["the host is Bitbucket", true, "bitbucket"], - ["the host is Azure DevOps", true, "azure-devops"], - ] as const)("does not offer the in-panel action when %s", (_name, enabled, kind) => { - testState.pullRequestsEnabled = enabled; - for (const data of [ - status({ - sourceControlProvider: { kind, name: "Host", baseUrl: "https://host.test" }, - pr: OPEN_MR, - }), - legacyStatus({ - sourceControlProvider: { kind, name: "Host", baseUrl: "https://host.test" }, - pr: OPEN_MR, - }), - ]) { - testState.statusQuery.data = data; + ["Pull Requests is turned off", false, true, "gitlab"], + ["the host is Bitbucket", true, true, "bitbucket"], + ["the host is Azure DevOps", true, true, "azure-devops"], + ["the server cannot read pull requests", true, false, "gitlab"], + ] as const)( + "opens View in the browser and offers no browser item when %s", + async (_name, enabled, reads, kind) => { + testState.pullRequestsEnabled = enabled; + testState.pullRequestsReads = reads; + for (const build of CLEAN_LADDERS) { + testState.openPullRequestLink.mockClear(); + testState.statusQuery.data = build({ + sourceControlProvider: { kind, name: "Host", baseUrl: "https://host.test" }, + pr: OPEN_MR, + }); + render(buildProps()); + expect(menuItemByText("in browser")).toBeUndefined(); + (buttonsByText("View ")[0] ?? menuItemByText("View "))?.onClick?.(); + await flushPromises(); + expect(testState.openPullRequestLink).toHaveBeenCalledWith( + (testState.localApi as { shell: unknown }).shell, + OPEN_MR.url, + ); + expect(testState.openPullRequest).not.toHaveBeenCalled(); + } + }, + ); + + it("still opens the panel when the connection is down and the repository is unknown", () => { + testState.pullRequestsContext = undefined; + testState.statusQuery.data = status({ pr: OPEN_MR }); + render(buildProps()); + (buttonsByText("View PR")[0] ?? menuItemByText("View PR"))?.onClick?.(); + expect(testState.openPullRequest).toHaveBeenCalledTimes(1); + expect(testState.openPullRequestLink).not.toHaveBeenCalled(); + }); + + it("opens View PR in the browser when the pull request belongs to another repository", async () => { + // origin is a fork; the status lookup found the parent's pull request. + testState.pullRequestsContext = { status: "available", repository: "fork/repo" }; + for (const build of CLEAN_LADDERS) { + testState.openPullRequestLink.mockClear(); + testState.statusQuery.data = build({ + pr: { ...OPEN_MR, url: "https://host.test/team/repo/pull/89" }, + }); render(buildProps()); - expect(captured.menuItems.map((item) => flattenText(item.children))).not.toContainEqual( - expect.stringContaining("in panel"), - ); - expect(menuItemByText("View")).toBeDefined(); + expect(menuItemByText("Open PR in browser")).toBeUndefined(); + (buttonsByText("View PR")[0] ?? menuItemByText("View PR"))?.onClick?.(); + await flushPromises(); + expect(testState.openPullRequestLink).toHaveBeenCalledTimes(1); + expect(testState.openPullRequest).not.toHaveBeenCalled(); } }); + it("opens View PR in the panel when the pull request belongs to the addressed repository", () => { + testState.pullRequestsContext = { status: "available", repository: "team/repo" }; + testState.statusQuery.data = status({ + pr: { ...OPEN_MR, url: "https://host.test/team/repo/pull/89" }, + }); + render(buildProps()); + (buttonsByText("View PR")[0] ?? menuItemByText("View PR"))?.onClick?.(); + expect(testState.openPullRequest).toHaveBeenCalledTimes(1); + }); + it("opens the created merge request beside the thread on Done", async () => { testState.statusQuery.data = status({ refName: "feature/test", @@ -968,11 +1032,13 @@ describe("SourceControlPanel", () => { }); it.each([ - ["Pull Requests is turned off", false, "gitlab"], - ["the host is Bitbucket", true, "bitbucket"], - ["the host is Azure DevOps", true, "azure-devops"], - ] as const)("does not open the created request on Done when %s", async (_name, enabled, kind) => { + ["Pull Requests is turned off", false, "gitlab", true], + ["the host is Bitbucket", true, "bitbucket", true], + ["the host is Azure DevOps", true, "azure-devops", true], + ["the server cannot read pull requests", true, "gitlab", false], + ] as const)("does not open the created request on Done when %s", async (_name, enabled, kind, reads) => { testState.pullRequestsEnabled = enabled; + testState.pullRequestsReads = reads; testState.statusQuery.data = status({ refName: "feature/test", hasUpstream: false, From 78046e199932b61af1732246dd430a07004de5ba Mon Sep 17 00:00:00 2001 From: mubeda <1380447+mubeda@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:09:35 -0300 Subject: [PATCH 009/242] fix(web): open View PR in the browser when the panel would address another repository The request lookup uses the host CLI default repository while the panel addresses the checkout origin, so a pull request of the parent of a copy opened the wrong number in the panel. The pull request URL is now compared with the panel repository once its context is known. The create-PR Done handler shares the same canShowPullRequestInPanel rule, including the pullRequestsReads capability. Co-Authored-By: Claude Fable 5.2 --- .../src/components/GitActionsControl.logic.ts | 41 +++++++++++++++++++ .../components/SourceControlPanel.test.tsx | 39 ++++++++++-------- .../web/src/components/SourceControlPanel.tsx | 29 +++++++++---- 3 files changed, 84 insertions(+), 25 deletions(-) diff --git a/apps/web/src/components/GitActionsControl.logic.ts b/apps/web/src/components/GitActionsControl.logic.ts index 149555206..dedc7d004 100644 --- a/apps/web/src/components/GitActionsControl.logic.ts +++ b/apps/web/src/components/GitActionsControl.logic.ts @@ -2,6 +2,7 @@ import { VcsActionRemoteFailureError } from "@bibcode/client-runtime/state/vcs"; import type { GitRunStackedActionResult, GitStackedAction, + SourceControlProviderKind, VcsStatusResult, } from "@bibcode/contracts"; import { isTemporaryWorktreeBranch } from "@bibcode/shared/git"; @@ -11,6 +12,7 @@ import { getChangeRequestTerminology, type ChangeRequestTerminology, } from "../sourceControlPresentation"; +import { canOpenPullRequestInPanel } from "./pullRequests/pullRequestsAvailability"; export type GitActionIconName = "commit" | "push" | "pr"; @@ -324,6 +326,45 @@ export function resolveQuickAction( }; } +/** + * Whether a request can be shown in the thread's right panel: the setting is on, the host has + * request details, and the server reads pull requests. A disconnect is not lack of support. + */ +export function canShowPullRequestInPanel(input: { + readonly enabled: boolean; + readonly pullRequestsReads: boolean; + readonly providerKind: SourceControlProviderKind; +}): boolean { + return ( + input.pullRequestsReads && + canOpenPullRequestInPanel({ enabled: input.enabled, providerKind: input.providerKind }) + ); +} + +const REQUEST_PATH_MARKER = /\/(?:-\/)?(?:pull|merge_requests)\/\d+/; + +/** + * True when a request URL names a repository other than `repository` (the checkout's origin, + * as the panel addresses it). Source Control finds a branch's request through the host CLI's + * default repository, which can be the parent of a copy. An unknown repository or an + * unrecognised URL is "cannot tell", reported as false. + */ +export function isPullRequestInOtherRepository( + requestUrl: string, + repository: string | null, +): boolean { + if (repository === null) return false; + let pathname: string; + try { + pathname = new URL(requestUrl).pathname; + } catch { + return false; + } + const marker = REQUEST_PATH_MARKER.exec(pathname); + if (marker === null) return false; + return pathname.slice(1, marker.index).toLowerCase() !== repository.toLowerCase(); +} + const isRemoteFailure = Schema.is(VcsActionRemoteFailureError); /** diff --git a/apps/web/src/components/SourceControlPanel.test.tsx b/apps/web/src/components/SourceControlPanel.test.tsx index 2ade1df18..49e07d91a 100644 --- a/apps/web/src/components/SourceControlPanel.test.tsx +++ b/apps/web/src/components/SourceControlPanel.test.tsx @@ -1036,24 +1036,27 @@ describe("SourceControlPanel", () => { ["the host is Bitbucket", true, "bitbucket", true], ["the host is Azure DevOps", true, "azure-devops", true], ["the server cannot read pull requests", true, "gitlab", false], - ] as const)("does not open the created request on Done when %s", async (_name, enabled, kind, reads) => { - testState.pullRequestsEnabled = enabled; - testState.pullRequestsReads = reads; - testState.statusQuery.data = status({ - refName: "feature/test", - hasUpstream: false, - aheadCount: 1, - sourceControlProvider: { kind, name: "Host", baseUrl: "https://host.test" }, - }); - const props = buildProps(); - render(props); - buttonsByText("Push & create")[0]?.onClick?.(); - await flushPromises(); - render(props); - expect(captured.createPullRequest).toMatchObject({ open: true }); - captured.createPullRequest?.onDone?.({ number: 89, provider: kind }); - expect(testState.openPullRequest).not.toHaveBeenCalled(); - }); + ] as const)( + "does not open the created request on Done when %s", + async (_name, enabled, kind, reads) => { + testState.pullRequestsEnabled = enabled; + testState.pullRequestsReads = reads; + testState.statusQuery.data = status({ + refName: "feature/test", + hasUpstream: false, + aheadCount: 1, + sourceControlProvider: { kind, name: "Host", baseUrl: "https://host.test" }, + }); + const props = buildProps(); + render(props); + buttonsByText("Push & create")[0]?.onClick?.(); + await flushPromises(); + render(props); + expect(captured.createPullRequest).toMatchObject({ open: true }); + captured.createPullRequest?.onDone?.({ number: 89, provider: kind }); + expect(testState.openPullRequest).not.toHaveBeenCalled(); + }, + ); it.each([ ["a tracked branch", { hasUpstream: true, aheadCount: 1 }, true], diff --git a/apps/web/src/components/SourceControlPanel.tsx b/apps/web/src/components/SourceControlPanel.tsx index 80ed63a3a..7f81f1928 100644 --- a/apps/web/src/components/SourceControlPanel.tsx +++ b/apps/web/src/components/SourceControlPanel.tsx @@ -100,6 +100,8 @@ import { DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell"; import { joinWorkspacePath } from "./files/FileTreeContextMenu.logic"; import { buildMenuItems, + canShowPullRequestInPanel, + isPullRequestInOtherRepository, type DefaultBranchConfirmableAction, requiresDefaultBranchConfirmation, resolveDefaultBranchActionDialogCopy, @@ -139,7 +141,7 @@ import { GIT_MANAGER_STASH_MERGE_DISABLED_REASON } from "./gitManager/gitManager import { GitManagerInProgressStrip } from "./gitManager/GitManagerInProgressStrip"; import { GitManagerMergeDialog } from "./gitManager/merge/GitManagerMergeDialog"; import { GitManagerOperationBanner } from "./gitManager/toolbar/GitManagerOperationBanner"; -import { canOpenPullRequestInPanel } from "./pullRequests/pullRequestsAvailability"; +import { usePullRequestsContextQuery } from "./pullRequests/usePullRequestsContextQuery"; import { SourceControlMergeChanges } from "./SourceControlMergeChanges"; import { CodeReviewInstructionsDialog } from "./sourceControl/CodeReviewInstructionsDialog"; import { CodeReviewProjectPromptDialog } from "./sourceControl/CodeReviewProjectPromptDialog"; @@ -423,12 +425,24 @@ export default function SourceControlPanel({ // The panel can show the request only on a host that has it, with the setting on and a server // that reads pull requests. Otherwise View PR opens the browser. + const openPrUrl = status?.pr?.state === "open" ? status.pr.url : null; + const panelSupported = canShowPullRequestInPanel({ + enabled: pullRequestsEnabled, + pullRequestsReads: capabilities?.pullRequestsReads === true, + providerKind: status?.sourceControlProvider?.kind ?? "unknown", + }); + // The panel addresses the checkout's origin, while the request lookup may have used another + // repository. Until the context is known, the panel opens and explains itself. + const { query: pullRequestsContext } = usePullRequestsContextQuery({ + environmentId, + cwd: gitCwd, + enabled: panelSupported && openPrUrl !== null, + }); + const panelRepository = + pullRequestsContext.data?.status === "available" ? pullRequestsContext.data.repository : null; const canOpenInPanel = - capabilities?.pullRequestsReads === true && - canOpenPullRequestInPanel({ - enabled: pullRequestsEnabled, - providerKind: status?.sourceControlProvider?.kind ?? "unknown", - }); + panelSupported && + !(openPrUrl !== null && isPullRequestInOtherRepository(openPrUrl, panelRepository)); // Legacy servers (no staging areas) keep the chat-header cascade // (commit_push-first, commit-by-filePaths). The primary button and dropdown // below fork on `hasAreas`: this pair drives the legacy branch unchanged. @@ -1782,8 +1796,9 @@ export default function SourceControlPanel({ }} onDone={(request) => { if ( - canOpenPullRequestInPanel({ + canShowPullRequestInPanel({ enabled: pullRequestsEnabled, + pullRequestsReads: capabilities?.pullRequestsReads === true, providerKind: request.provider, }) ) From 5294821fc838dcaa3da698190c2c1e1b6d4ff90d Mon Sep 17 00:00:00 2001 From: mubeda <1380447+mubeda@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:10:59 -0300 Subject: [PATCH 010/242] test(web): specify deleting a remote branch from the Git Manager branch list A remote row gets Delete, blocked with a visible reason on its remote's default branch and on a name two remotes match. The dialog sends one remote-branch-delete for the confirmed row, re-reads the row on Confirm, shows a sign-in prompt inside itself and resumes the offer's request unchanged, and shows the remote's stderr refusal. These fail before the change (#397). Co-Authored-By: Claude Opus 5.5 --- .../gitManager/GitManagerToolbar.test.tsx | 279 +++++++++++++++++- .../dialogs/GitManagerBranchDialogs.test.tsx | 92 +++++- .../toolbar/GitManagerBranchDropdown.test.tsx | 61 +++- .../toolbar/remoteBranchRef.test.ts | 71 +++++ 4 files changed, 499 insertions(+), 4 deletions(-) create mode 100644 apps/web/src/components/gitManager/toolbar/remoteBranchRef.test.ts diff --git a/apps/web/src/components/gitManager/GitManagerToolbar.test.tsx b/apps/web/src/components/gitManager/GitManagerToolbar.test.tsx index 257fba141..3f9e7cc34 100644 --- a/apps/web/src/components/gitManager/GitManagerToolbar.test.tsx +++ b/apps/web/src/components/gitManager/GitManagerToolbar.test.tsx @@ -27,10 +27,14 @@ const h = vi.hoisted(() => ({ failureMessage: null as string | null, /** Failures for one operation tag only; `failureMessage` fails every operation. */ failures: {} as Record, + /** Full event sequences for one operation tag, emitted in order; the last one settles it. */ + events: {} as Record>, + runSignIn: vi.fn(), })); vi.mock("../../state/gitManager", () => ({ runGitManagerOperation: h.runOperation, + runGitSignIn: h.runSignIn, gitManagerEnvironment: { getRefs: h.refsAtom, signalWithDegradedFocusRefresh: h.signalAtom, @@ -143,7 +147,12 @@ vi.mock("./tags/GitManagerTagDialog", () => ({ vi.mock("./dialogs/GitManagerBranchDialogs", () => ({ GitManagerBranchDialogs: (props: Record) => { h.branchDialogProps.push(props); - return null; + return props.dialog === null ? null : ( +
+ {props.errorMessage as React.ReactNode} + {props.signInPrompt as React.ReactNode} +
+ ); }, })); @@ -222,7 +231,22 @@ beforeEach(() => { h.runOperation.mockReset(); h.failureMessage = null; h.failures = {}; + h.events = {}; + h.runSignIn.mockReset(); + h.runSignIn.mockImplementation(() => ({ + cancel: vi.fn(), + result: Promise.resolve({ _tag: "Success", value: { outcome: "signedIn", message: "" } }), + })); h.runOperation.mockImplementation((_registry, { input }, onEvent) => { + const sequence = h.events[input._tag]; + if (sequence !== undefined) { + delete h.events[input._tag]; + for (const event of sequence) onEvent(event); + return { + cancel: vi.fn(), + result: Promise.resolve({ _tag: "Success", value: sequence.at(-1) }), + }; + } const failure = h.failures[input._tag] ?? (h.failureMessage === null ? null : { code: "branch-exists", message: h.failureMessage }); @@ -730,6 +754,259 @@ describe("GitManagerToolbar", () => { expect(empty).toContain('No local tags.'); }); + describe("remote branch delete (#397)", () => { + const offer = { + remote: "origin", + destination: "https://gitlab.example.test/example-group/sample-project.git", + host: "gitlab.example.test", + direction: "push" as const, + }; + const resume = { + _tag: "remote-branch-delete" as const, + cwd: "/opaque/main", + projectId: "project-current" as never, + remote: "origin", + branch: "develop", + expectedDestination: offer.destination, + }; + const signInFailure: GitManagerOperationEvent = { + _tag: "failed", + operation: "remote-branch-delete", + code: "sign-in-required", + message: "Sign in to continue.", + blocked: null, + signIn: { ...offer, resume }, + }; + let container: HTMLDivElement; + let root: ReturnType; + + async function mount() { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + container = document.createElement("div"); + document.body.append(container); + root = createRoot(container); + await rerender(); + } + + async function rerender() { + await act(async () => + root.render( + undefined} + />, + ), + ); + } + + async function unmount() { + await act(async () => root.unmount()); + container.remove(); + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = false; + } + + const lastDialogProps = () => h.branchDialogProps.at(-1)!; + const clickButton = async (text: string) => { + const button = [...document.querySelectorAll("button")].find( + (entry) => entry.textContent === text, + ); + expect(button).toBeDefined(); + await act(async () => button!.click()); + }; + const submit = async (submission: Record) => { + const onSubmit = lastDialogProps().onSubmit as (value: unknown) => Promise; + await act(async () => onSubmit(submission)); + }; + const sentInputs = () => h.runOperation.mock.calls.map((call) => call[1].input); + + it.each([ + ["with a local branch of the same name", true], + ["for a remote-only branch", false], + ])("deletes the remote row %s, then the row is gone", async (_, withLocal) => { + const local = withLocal ? [ref("develop")] : []; + h.snapshot = { + ...refsSnapshot(), + localBranches: [...refsSnapshot().localBranches, ...local], + remoteBranches: [ref("origin/main", { isDefault: true }), ref("origin/develop")], + }; + await mount(); + try { + const deleteButton = container.querySelector( + '[aria-label="Delete remote branch origin/develop"]', + ); + await act(async () => deleteButton!.click()); + expect(lastDialogProps().dialog).toMatchObject({ + kind: "delete-remote", + remote: "origin", + remoteBranch: "develop", + }); + + await submit({ kind: "delete-remote", remote: "origin", branch: "develop" }); + + expect(sentInputs()).toEqual([ + { + _tag: "remote-branch-delete", + cwd: "/opaque/main", + projectId: "project-current", + remote: "origin", + branch: "develop", + }, + ]); + expect(lastDialogProps().dialog).toBeNull(); + expect(h.refreshRefs).toHaveBeenCalled(); + + h.snapshot = { ...h.snapshot, remoteBranches: [ref("origin/main", { isDefault: true })] }; + await act(async () => + useGitManagerStore.getState().setOpenDropdown(currentProject, "branch"), + ); + await rerender(); + expect( + container.querySelector('[aria-label="Delete remote branch origin/develop"]'), + ).toBeNull(); + expect(container.querySelector('[aria-label="Delete develop"]') !== null).toBe(withLocal); + } finally { + await unmount(); + } + }); + + it("offers sign-in inside the dialog and resumes the offer's request unchanged", async () => { + h.snapshot = { ...refsSnapshot(), remoteBranches: [ref("origin/develop")] }; + h.events = { "remote-branch-delete": [signInFailure] }; + await mount(); + try { + await act(async () => + container + .querySelector('[aria-label="Delete remote branch origin/develop"]')! + .click(), + ); + await submit({ kind: "delete-remote", remote: "origin", branch: "develop" }); + expect(lastDialogProps().dialog).not.toBeNull(); + expect(container.querySelector('[role="dialog"]')?.textContent).toContain( + "gitlab.example.test", + ); + + await clickButton("Sign in"); + + expect(h.runSignIn).toHaveBeenCalledTimes(1); + expect(sentInputs()).toEqual([ + { + _tag: "remote-branch-delete", + cwd: "/opaque/main", + projectId: "project-current", + remote: "origin", + branch: "develop", + }, + resume, + ]); + expect(lastDialogProps().dialog).toBeNull(); + } finally { + await unmount(); + } + }); + + it("keeps the dialog open with the failure when sign-in is declined", async () => { + h.snapshot = { ...refsSnapshot(), remoteBranches: [ref("origin/develop")] }; + h.events = { "remote-branch-delete": [signInFailure] }; + await mount(); + try { + await act(async () => + container + .querySelector('[aria-label="Delete remote branch origin/develop"]')! + .click(), + ); + await submit({ kind: "delete-remote", remote: "origin", branch: "develop" }); + await clickButton("Not now"); + + expect(sentInputs()).toHaveLength(1); + expect(lastDialogProps().dialog).not.toBeNull(); + expect(lastDialogProps().errorMessage).toBe( + "Authentication failed. Check the configured credentials and try again.", + ); + } finally { + await unmount(); + } + }); + + it("shows the remote's rejection text and keeps the dialog open", async () => { + const rejection = " ! [remote rejected] develop (protected branch hook declined)"; + h.snapshot = { ...refsSnapshot(), remoteBranches: [ref("origin/develop")] }; + h.events = { + "remote-branch-delete": [ + { _tag: "started", operation: "remote-branch-delete" }, + { _tag: "output", operation: "remote-branch-delete", stream: "stderr", text: rejection }, + { + _tag: "failed", + operation: "remote-branch-delete", + code: "git-command-failed", + message: "The Git command failed.", + blocked: null, + }, + ], + }; + await mount(); + try { + await act(async () => + container + .querySelector('[aria-label="Delete remote branch origin/develop"]')! + .click(), + ); + await submit({ kind: "delete-remote", remote: "origin", branch: "develop" }); + + expect(lastDialogProps().dialog).not.toBeNull(); + expect(lastDialogProps().errorMessage).toContain("protected branch hook declined"); + } finally { + await unmount(); + } + }); + + it("keeps local delete with its remote and now offers sign-in for it", async () => { + h.snapshot = { + ...refsSnapshot(), + localBranches: [ + ...refsSnapshot().localBranches, + ref("develop", { upstream: "origin/develop" }), + ], + remoteBranches: [ref("origin/develop")], + }; + h.events = { "branch-delete": [{ ...signInFailure, operation: "branch-delete" }] }; + await mount(); + try { + await act(async () => + container.querySelector('[aria-label="Delete develop"]')!.click(), + ); + expect(lastDialogProps().dialog).toMatchObject({ kind: "delete", existsUpstream: true }); + await submit({ kind: "delete", name: "develop", deleteRemote: true }); + + expect(sentInputs()).toEqual([ + { + _tag: "branch-delete", + cwd: "/opaque/main", + projectId: "project-current", + name: "develop", + force: true, + deleteRemote: true, + }, + ]); + expect(container.querySelector('[role="dialog"]')?.textContent).toContain( + "gitlab.example.test", + ); + await clickButton("Sign in"); + expect(sentInputs().at(-1)).toEqual(resume); + } finally { + await unmount(); + } + }); + }); + it("skips the live signal subscription without disabling explicit repository reads", () => { h.snapshot = refsSnapshot(); diff --git a/apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.test.tsx b/apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.test.tsx index 2be1f65c4..2fd143f3d 100644 --- a/apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.test.tsx +++ b/apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.test.tsx @@ -415,12 +415,100 @@ describe("GitManagerBranchDialogs", () => { expect(renames).toEqual([{ kind: "rename", name: "feature", newName: "feature-two" }]); }); + async function renderRemoteDelete( + remoteRefs: ReadonlyArray, + extra: Partial> = {}, + ) { + const submissions: GitManagerBranchDialogSubmission[] = []; + await act(async () => + root?.render( + undefined} + onSubmit={(submission) => { + submissions.push(submission); + return Promise.resolve(); + }} + {...extra} + />, + ), + ); + return submissions; + } + + it("confirms a remote branch delete that names the remote and keeps the local branch", async () => { + const submissions = await renderRemoteDelete([branch("origin/feature/a")]); + + expect(document.querySelector("h2")?.textContent).toBe("Delete Remote Branch?"); + const text = document.body.textContent ?? ""; + expect(text).toContain("feature/a"); + expect(text).toContain("origin"); + expect(text).toContain("A local branch with the same name is kept."); + expect(text).toContain("The remote may refuse to delete a protected branch."); + const deleteButton = buttonWithText("Delete remote branch"); + expect(deleteButton.disabled).toBe(true); + await act(async () => deleteButton.click()); + expect(submissions).toEqual([]); + + await confirmDelete(); + expect(deleteButton.disabled).toBe(false); + await act(async () => deleteButton.click()); + expect(submissions).toEqual([{ kind: "delete-remote", remote: "origin", branch: "feature/a" }]); + }); + + it("sends nothing when the remote branch is gone from a newer snapshot", async () => { + const submissions = await renderRemoteDelete([branch("origin/feature/a")]); + await confirmDelete(); + await renderRemoteDelete([branch("origin/other")]); + + await act(async () => buttonWithText("Delete remote branch").click()); + expect(submissions).toEqual([]); + expect(document.body.textContent).toContain("This remote branch no longer exists."); + }); + + it("blocks a remote branch that became the remote's default while the dialog was open", async () => { + const submissions = await renderRemoteDelete([branch("origin/feature/a")]); + await confirmDelete(); + await renderRemoteDelete([branch("origin/feature/a", { isDefault: true })]); + + await act(async () => buttonWithText("Delete remote branch").click()); + expect(submissions).toEqual([]); + expect(document.body.textContent).toContain( + "Delete is blocked: this is the remote's default branch.", + ); + }); + + it("shows a Git error and a sign-in prompt inside the open dialog", async () => { + const error = "remote: error: protected branch hook declined"; + await renderRemoteDelete([branch("origin/feature/a")], { + errorMessage: error, + signInPrompt:

Sign in to example.test?

, + }); + + expect(document.body.textContent).toContain(error); + expect(document.body.textContent).toContain("Sign in to example.test?"); + expect(buttonWithText("Delete remote branch")).toBeDefined(); + }); + it("shows the server's rename reason and not an unrelated one", async () => { - const message = "Rename is blocked: the worktree at /opaque/feature has this branch checked out."; + const message = + "Rename is blocked: the worktree at /opaque/feature has this branch checked out."; await renderBranchDialog({ kind: "rename", branch: branch("feature", { - blocked: [MERGE_DIRTY, { operation: "rename-branch", code: "worktree-checked-out", message }], + blocked: [ + MERGE_DIRTY, + { operation: "rename-branch", code: "worktree-checked-out", message }, + ], }), }); diff --git a/apps/web/src/components/gitManager/toolbar/GitManagerBranchDropdown.test.tsx b/apps/web/src/components/gitManager/toolbar/GitManagerBranchDropdown.test.tsx index ef4677ea5..3b8338982 100644 --- a/apps/web/src/components/gitManager/toolbar/GitManagerBranchDropdown.test.tsx +++ b/apps/web/src/components/gitManager/toolbar/GitManagerBranchDropdown.test.tsx @@ -297,6 +297,61 @@ describe("GitManagerBranchDropdown", () => { expect(container.textContent).not.toContain("Remote branches"); }); + it("offers Delete and no Rename on a remote row", async () => { + const onDeleteRemoteBranch = vi.fn(); + const remote = branch("origin/feature/a"); + await renderDropdown([], { + remoteRefs: [remote], + remotes: ["origin"], + onDeleteRemoteBranch, + }); + + expect(container.querySelector('[aria-label="Rename origin/feature/a"]')).toBeNull(); + const deleteButton = container.querySelector( + '[aria-label="Delete remote branch origin/feature/a"]', + ); + expect(deleteButton?.disabled).toBe(false); + await act(async () => deleteButton!.click()); + expect(onDeleteRemoteBranch).toHaveBeenCalledWith(remote); + }); + + it.each([ + [ + "the remote's default branch", + branch("upstream/trunk", { isDefault: true }), + ["origin", "upstream"], + "Delete is blocked: this is the remote's default branch.", + ], + [ + "a name two remotes match", + branch("team/fork/x"), + ["team", "team/fork"], + "Delete is blocked: two remotes match this name. Delete it from a terminal.", + ], + ])( + "disables Delete on %s with a visible, described reason", + async (_, remote, remotes, reason) => { + const onDeleteRemoteBranch = vi.fn(); + await renderDropdown([], { remoteRefs: [remote], remotes, onDeleteRemoteBranch }); + + const deleteButton = container.querySelector( + `[aria-label="Delete remote branch ${remote.name}"]`, + ); + expect(deleteButton).toMatchObject({ disabled: true, title: reason }); + expect(container.textContent).toContain(reason); + const describedBy = deleteButton!.getAttribute("aria-describedby")!.split(" "); + expect(describedBy.map((id) => document.getElementById(id)?.textContent)).toContain(reason); + await act(async () => deleteButton!.click()); + expect(onDeleteRemoteBranch).not.toHaveBeenCalled(); + // Checkout of the remote row is a different action and stays available. + expect( + container.querySelector( + `[aria-label="Check out remote branch ${remote.name}"]`, + )?.disabled, + ).toBe(false); + }, + ); + const dirty = (operation: string, label: string) => ({ operation, code: "dirty-working-tree" as const, @@ -306,7 +361,11 @@ describe("GitManagerBranchDropdown", () => { it("lets a dirty checkout through to the Stash or Bring choice", async () => { const callbacks = await renderDropdown([ branch("feature", { - blocked: [dirty("checkout", "Checkout"), dirty("merge", "Merge"), dirty("rebase", "Rebase")], + blocked: [ + dirty("checkout", "Checkout"), + dirty("merge", "Merge"), + dirty("rebase", "Rebase"), + ], }), ]); diff --git a/apps/web/src/components/gitManager/toolbar/remoteBranchRef.test.ts b/apps/web/src/components/gitManager/toolbar/remoteBranchRef.test.ts new file mode 100644 index 000000000..857e7e58b --- /dev/null +++ b/apps/web/src/components/gitManager/toolbar/remoteBranchRef.test.ts @@ -0,0 +1,71 @@ +import type { GitManagerRefEntry } from "@bibcode/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { remoteDeleteBlockedReason, splitRemoteBranchRef } from "./remoteBranchRef"; + +function remoteRef(name: string, isDefault = false): GitManagerRefEntry { + return { + name, + tipSha: "a".repeat(40), + upstream: null, + ahead: 0, + behind: 0, + current: false, + isDefault, + worktreePath: null, + blocked: [], + }; +} + +describe("splitRemoteBranchRef", () => { + it("splits on the remote that prefixes the name, keeping slashes in the branch", () => { + expect(splitRemoteBranchRef("origin/feature/a", ["origin"])).toEqual({ + remote: "origin", + branch: "feature/a", + }); + }); + + it("gives null when no remote prefixes the name", () => { + expect(splitRemoteBranchRef("upstream/main", ["origin"])).toBeNull(); + expect(splitRemoteBranchRef("origin", ["origin"])).toBeNull(); + }); + + it("is ambiguous when two remotes prefix the name", () => { + expect(splitRemoteBranchRef("team/fork/x", ["team", "team/fork"])).toBe("ambiguous"); + }); + + it("does not take a remote whose name is only a text prefix", () => { + expect(splitRemoteBranchRef("origin-fork/x", ["origin", "origin-fork"])).toEqual({ + remote: "origin-fork", + branch: "x", + }); + }); +}); + +describe("remoteDeleteBlockedReason", () => { + it("blocks the remote's default branch", () => { + const ref = remoteRef("origin/trunk", true); + expect(remoteDeleteBlockedReason(ref, splitRemoteBranchRef(ref.name, ["origin"]))).toBe( + "Delete is blocked: this is the remote's default branch.", + ); + }); + + it("blocks a name two remotes match", () => { + expect(remoteDeleteBlockedReason(remoteRef("team/fork/x"), "ambiguous")).toBe( + "Delete is blocked: two remotes match this name. Delete it from a terminal.", + ); + }); + + it("blocks a name no remote matches", () => { + expect(remoteDeleteBlockedReason(remoteRef("gone/x"), null)).toBe( + "Delete is blocked: the remote of this branch is unknown.", + ); + }); + + it("allows other branches, including the local default's namesake on a remote", () => { + const ref = remoteRef("upstream/main"); + expect( + remoteDeleteBlockedReason(ref, splitRemoteBranchRef(ref.name, ["origin", "upstream"])), + ).toBeNull(); + }); +}); From 311beb1909513b42b0ba3822239aea8c428e509e Mon Sep 17 00:00:00 2001 From: mubeda <1380447+mubeda@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:12:37 -0300 Subject: [PATCH 011/242] feat(web): delete a remote branch from the Git Manager branch list A remote row now has Delete. It opens a confirmation that names the remote and the branch, keeps any local branch, and says the remote may refuse a protected branch. Confirm sends remote-branch-delete for that row, re-read from the newest snapshot. The row's remote default branch, and a name two remotes match, keep Delete off with a visible reason; the server checks again before it deletes anything. The toolbar never offered sign-in (#402): only the panel read a failure's sign-in offer. Both now use one hook, useGitManagerSignIn, and the toolbar shows the prompt inside an open branch dialog, whose resumed request closes it on success. Git's stderr refusal joins the failure summary in the dialog. Closes #402 Co-Authored-By: Claude Opus 5.5 --- .../components/gitManager/GitManagerPanel.tsx | 34 +----- .../gitManager/GitManagerToolbar.tsx | 79 +++++++++++- .../dialogs/GitManagerBranchDialogs.tsx | 113 +++++++++++++++++- .../toolbar/GitManagerBranchDropdown.tsx | 65 +++++++++- .../gitManager/toolbar/remoteBranchRef.ts | 38 ++++++ .../gitManager/useGitManagerSignIn.ts | 62 ++++++++++ 6 files changed, 350 insertions(+), 41 deletions(-) create mode 100644 apps/web/src/components/gitManager/toolbar/remoteBranchRef.ts create mode 100644 apps/web/src/components/gitManager/useGitManagerSignIn.ts diff --git a/apps/web/src/components/gitManager/GitManagerPanel.tsx b/apps/web/src/components/gitManager/GitManagerPanel.tsx index 88766eee9..10c958219 100644 --- a/apps/web/src/components/gitManager/GitManagerPanel.tsx +++ b/apps/web/src/components/gitManager/GitManagerPanel.tsx @@ -95,8 +95,7 @@ import { GitManagerTagDialog } from "./tags/GitManagerTagDialog"; import { GitManagerTagsView, type GitManagerTagRowAction } from "./tags/GitManagerTagsView"; import { GitManagerOperationBanner } from "./toolbar/GitManagerOperationBanner"; import { GitSignInPrompt } from "../gitSignIn/GitSignInPrompt"; -import { SIGN_IN_REPEATED_MESSAGE } from "../gitSignIn/gitSignIn.logic"; -import { useGitSignInFlow } from "../gitSignIn/useGitSignInFlow"; +import { useGitManagerSignIn } from "./useGitManagerSignIn"; import { useCheckoutStatusRereads } from "./useCheckoutStatusRereads"; import { GitManagerRepositoryUnavailable } from "./GitManagerRepositoryUnavailable"; import { @@ -495,36 +494,13 @@ const GitManagerRepositorySurfaces = memo(function GitManagerRepositorySurfaces( revalidateRefs(); if (stashPaneOpen) revalidateStashes(); }, [revalidateRefs, revalidateStashes, stashPaneOpen]); - const signIn = useGitSignInFlow(environmentId); - const offerSignIn = signIn.offer; - // Set while the request a sign-in resumed runs: a second `sign-in-required` is not offered again. - const resumingAfterSignInRef = useRef(false); const executeOperationRef = useRef< ((input: GitManagerOperationRequest) => Promise) | null >(null); - const presentOperationEvent = useCallback( - (event: GitManagerOperationEvent): GitManagerOperationEvent => { - if (event._tag !== "failed" || event.signIn === undefined) return event; - const { signIn: offer, ...failure } = event; - if (resumingAfterSignInRef.current) { - return { ...failure, message: SIGN_IN_REPEATED_MESSAGE }; - } - offerSignIn({ - offer, - cwd: offer.resume.cwd, - projectId: offer.resume.projectId, - onSignedIn: () => { - resumingAfterSignInRef.current = true; - void executeOperationRef.current?.(offer.resume).finally(() => { - resumingAfterSignInRef.current = false; - }); - }, - onEnded: (code, message) => setOperationEvent({ ...failure, code, message, blocked: null }), - }); - return failure; - }, - [offerSignIn], - ); + const { flow: signIn, present: presentOperationEvent } = useGitManagerSignIn(environmentId, { + resume: (request) => executeOperationRef.current?.(request) ?? Promise.resolve(false), + onEnded: setOperationEvent, + }); const executeOperation = useCallback( async ( input: GitManagerOperationRequest, diff --git a/apps/web/src/components/gitManager/GitManagerToolbar.tsx b/apps/web/src/components/gitManager/GitManagerToolbar.tsx index 0aced608a..4b3e898b6 100644 --- a/apps/web/src/components/gitManager/GitManagerToolbar.tsx +++ b/apps/web/src/components/gitManager/GitManagerToolbar.tsx @@ -28,9 +28,11 @@ import { type GitManagerBranchDialogSubmission, } from "./dialogs/GitManagerBranchDialogs"; import { GitManagerSwitchWithChangesDialog } from "./dialogs/GitManagerSwitchWithChangesDialog"; +import { GitSignInPrompt } from "../gitSignIn/GitSignInPrompt"; import { newBranchDialog } from "./toolbar/branchCreateBase"; import { GitManagerBranchDropdown } from "./toolbar/GitManagerBranchDropdown"; import { GitManagerOperationBanner } from "./toolbar/GitManagerOperationBanner"; +import { splitRemoteBranchRef } from "./toolbar/remoteBranchRef"; import { GitManagerSyncButton, type SyncOperationKind, @@ -39,6 +41,7 @@ import { import { resolveSyncState, type SyncState } from "./toolbar/syncButton.logic"; import { GitManagerTagDialog } from "./tags/GitManagerTagDialog"; import type { RepositoryUnavailable } from "./gitManagerRepositoryAvailability"; +import { useGitManagerSignIn } from "./useGitManagerSignIn"; import { Menu, MenuItem, @@ -131,6 +134,7 @@ function leaveChangesSwitchFailure( const EMPTY_BRANCHES: ReadonlyArray = Object.freeze([]); const EMPTY_TAG_NAMES: ReadonlyArray = Object.freeze([]); +const EMPTY_REMOTES: ReadonlyArray = Object.freeze([]); const LOADING_SYNC_STATE: SyncState = Object.freeze({ kind: "running", label: "Loading repository state…", @@ -335,6 +339,19 @@ export const GitManagerToolbar = memo(function GitManagerToolbar({ [], ); + const executeOperationRef = useRef< + ((input: GitManagerOperationRequest) => Promise) | null + >(null); + const { flow: signIn, present: presentOperationEvent } = useGitManagerSignIn(environmentId, { + // A resumed request that succeeds closes the dialog that sent the original one. + resume: async (request) => { + if (await executeOperationRef.current?.(request)) setBranchDialog(null); + }, + onEnded: (failure) => { + setOperationEvent(failure); + setOperationError(failure.message); + }, + }); const executeOperation = useCallback( async (input: GitManagerOperationRequest): Promise => { lastFailureCodeRef.current = null; @@ -342,11 +359,20 @@ export const GitManagerToolbar = memo(function GitManagerToolbar({ setOperationError(null); setIsOperationRunning(true); setOperationEvent({ _tag: "started", operation: input._tag }); - const handle = runGitManagerOperation(registry, { environmentId, input }, (event) => { + // Git's own refusal (a protected branch, a rejected push) arrives on stderr before the + // failure summary; the dialog shows both. + let stderr = ""; + const handle = runGitManagerOperation(registry, { environmentId, input }, (received) => { + if (received._tag === "output" && received.stream === "stderr") stderr += received.text; + const event = presentOperationEvent(received); setOperationEvent(event); if (event._tag === "failed") { lastFailureCodeRef.current = event.code; - setOperationError(event.blocked?.message ?? event.message); + const gitError = stderr.trim(); + setOperationError( + event.blocked?.message ?? + (gitError === "" ? event.message : `${event.message}\n${gitError}`), + ); } }); activeOperationRef.current = handle; @@ -370,8 +396,11 @@ export const GitManagerToolbar = memo(function GitManagerToolbar({ } return result.value._tag === "finished"; }, - [environmentId, revalidateRefs, registry], + [environmentId, presentOperationEvent, revalidateRefs, registry], ); + useEffect(() => { + executeOperationRef.current = executeOperation; + }, [executeOperation]); const cancelOperation = useCallback(() => { const active = activeOperationRef.current; if (active === null) return; @@ -463,6 +492,21 @@ export const GitManagerToolbar = memo(function GitManagerToolbar({ setBranchDialog({ kind: "delete", branch, existsUpstream: branch.upstream !== null }), [], ); + const remotes = snapshot?.remotes ?? EMPTY_REMOTES; + const deleteRemoteBranch = useCallback( + (branch: GitManagerRefEntry) => { + const split = splitRemoteBranchRef(branch.name, remotes); + if (split === null || split === "ambiguous") return; + setOperationError(null); + setBranchDialog({ + kind: "delete-remote", + branch, + remote: split.remote, + remoteBranch: split.branch, + }); + }, + [remotes], + ); const mergeIntoCurrent = useCallback( (branch: GitManagerRefEntry) => { if (stashMergeDisabledReason !== null) { @@ -519,6 +563,15 @@ export const GitManagerToolbar = memo(function GitManagerToolbar({ deleteRemote: submission.deleteRemote, }; break; + case "delete-remote": + request = { + _tag: "remote-branch-delete", + cwd: selectedWorktreeCwd, + projectId, + remote: submission.remote, + branch: submission.branch, + }; + break; } if (await executeOperation(request)) setBranchDialog(null); }, @@ -594,6 +647,17 @@ export const GitManagerToolbar = memo(function GitManagerToolbar({ tagMenuDisabledReason ?? (tagTargetSha === null ? "Create a commit before creating a tag." : null); const tagRemote = snapshot?.remotes.includes(remote) === true ? remote : null; + // A modal branch dialog covers the toolbar, so the prompt for its request shows inside it. + const signInPrompt = + signIn.state === null ? null : ( + + ); return (
@@ -685,7 +749,9 @@ export const GitManagerToolbar = memo(function GitManagerToolbar({ remoteRefs={snapshot?.remoteBranches ?? EMPTY_BRANCHES} selectedWorktreeCwd={selectedWorktreeCwd} onCreateBranch={createBranch} + remotes={remotes} onDeleteBranch={deleteBranch} + onDeleteRemoteBranch={deleteRemoteBranch} onMergeInto={mergeIntoCurrent} onRenameBranch={renameBranch} onSelectBranch={selectBranch} @@ -809,12 +875,17 @@ export const GitManagerToolbar = memo(function GitManagerToolbar({
- + {signInPrompt !== null && branchDialog === null ? ( + signInPrompt + ) : ( + + )} /`. */ + readonly branch: GitManagerRefEntry; + readonly remote: string; + readonly remoteBranch: string; }; export type GitManagerBranchDialogSubmission = @@ -52,7 +60,8 @@ export type GitManagerBranchDialogSubmission = readonly checkout: boolean; } | { readonly kind: "rename"; readonly name: string; readonly newName: string } - | { readonly kind: "delete"; readonly name: string; readonly deleteRemote: boolean }; + | { readonly kind: "delete"; readonly name: string; readonly deleteRemote: boolean } + | { readonly kind: "delete-remote"; readonly remote: string; readonly branch: string }; export interface GitManagerBranchDialogsProps { readonly dialog: GitManagerBranchDialog | null; @@ -62,6 +71,8 @@ export interface GitManagerBranchDialogsProps { readonly busy: boolean; readonly errorMessage: string | null; readonly disabledReason?: string | null; + /** A Git sign-in prompt for the request this dialog sent; shown inside the modal dialog. */ + readonly signInPrompt?: ReactNode; readonly onClose: () => void; readonly onSubmit: (submission: GitManagerBranchDialogSubmission) => Promise; } @@ -92,7 +103,7 @@ interface SharedDialogProps { function DialogError({ message }: { readonly message: string | null }) { return message === null ? null : ( -

+

{message}

); @@ -386,12 +397,14 @@ function DeleteBranchDialog({ existsUpstream, busy, errorMessage, + signInPrompt, disabledReason: capabilityDisabledReason, onClose, onSubmit, }: Omit & { readonly branch: GitManagerRefEntry; readonly existsUpstream: boolean; + readonly signInPrompt: ReactNode; }) { const [confirmed, setConfirmed] = useState(false); const [deleteRemote, setDeleteRemote] = useState(false); @@ -438,6 +451,7 @@ function DeleteBranchDialog({ ) : null} + {signInPrompt} + + Delete remote branch + + + + + ); +} + export const GitManagerBranchDialogs = memo(function GitManagerBranchDialogs({ dialog, refs, @@ -464,6 +553,7 @@ export const GitManagerBranchDialogs = memo(function GitManagerBranchDialogs({ busy, errorMessage, disabledReason = null, + signInPrompt = null, onClose, onSubmit, }: GitManagerBranchDialogsProps) { @@ -492,6 +582,23 @@ export const GitManagerBranchDialogs = memo(function GitManagerBranchDialogs({ disabledReason={disabledReason} errorMessage={errorMessage} existsUpstream={dialog.existsUpstream} + signInPrompt={signInPrompt} + onClose={onClose} + onSubmit={onSubmit} + /> + ); + case "delete-remote": + return ( + diff --git a/apps/web/src/components/gitManager/toolbar/GitManagerBranchDropdown.tsx b/apps/web/src/components/gitManager/toolbar/GitManagerBranchDropdown.tsx index 87b056983..2267dbb60 100644 --- a/apps/web/src/components/gitManager/toolbar/GitManagerBranchDropdown.tsx +++ b/apps/web/src/components/gitManager/toolbar/GitManagerBranchDropdown.tsx @@ -34,8 +34,10 @@ import { useGitManagerStore, } from "../../../gitManagerStore"; import { groupBranches } from "./branchGrouping"; +import { remoteDeleteBlockedReason, splitRemoteBranchRef } from "./remoteBranchRef"; const BRANCH_ROW_HEIGHT = 30; +const EMPTY_REMOTES: ReadonlyArray = Object.freeze([]); const BRANCH_LIST_STYLE: CSSProperties = Object.freeze({ height: "15rem" }); const KNOWN_BLOCKED_CODES = new Set([ "worktree-checked-out", @@ -100,6 +102,8 @@ function branchRowPropsEqual( previous.onMergeInto === next.onMergeInto && previous.onRenameBranch === next.onRenameBranch && previous.onDeleteBranch === next.onDeleteBranch && + previous.remoteDeleteDisabledReason === next.remoteDeleteDisabledReason && + previous.onDeleteRemoteBranch === next.onDeleteRemoteBranch && left.name === right.name && left.tipSha === right.tipSha && left.upstream === right.upstream && @@ -124,6 +128,9 @@ interface GitManagerBranchRowProps { readonly onMergeInto: (ref: GitManagerRefEntry) => void; readonly onRenameBranch: (ref: GitManagerRefEntry) => void; readonly onDeleteBranch: (ref: GitManagerRefEntry) => void; + /** Why a remote row's Delete is off; null when it is available or the row is local. */ + readonly remoteDeleteDisabledReason: string | null; + readonly onDeleteRemoteBranch: ((ref: GitManagerRefEntry) => void) | undefined; } const GitManagerBranchRow = memo(function GitManagerBranchRow({ @@ -138,6 +145,8 @@ const GitManagerBranchRow = memo(function GitManagerBranchRow({ onMergeInto, onRenameBranch, onDeleteBranch, + remoteDeleteDisabledReason, + onDeleteRemoteBranch, }: GitManagerBranchRowProps) { const redirectPath = refEntry.worktreePath !== null && refEntry.worktreePath !== selectedWorktreeCwd @@ -174,6 +183,11 @@ const GitManagerBranchRow = memo(function GitManagerBranchRow({ const disabled = capabilityDisabledReason !== null || blockedReason !== null || currentMergeReason !== null; const title = displayReason ?? undefined; + const rowNote = displayReason ?? remoteDeleteDisabledReason; + const remoteDeleteDescriptionId = + remoteDeleteDisabledReason === null + ? undefined + : `git-manager-branch-remote-${encodeURIComponent(refEntry.name)}-delete`; const activate = useCallback(() => { if (disabled) return; if (mergeMode) { @@ -214,10 +228,8 @@ const GitManagerBranchRow = memo(function GitManagerBranchRow({ ) : null} {refEntry.name} - {displayReason === null ? null : ( - - {displayReason} - + {rowNote === null ? null : ( + {rowNote} )} {redirectPath === null ? null : ( @@ -226,7 +238,21 @@ const GitManagerBranchRow = memo(function GitManagerBranchRow({ )} - {isRemote ? null : ( + {isRemote ? ( + onDeleteRemoteBranch === undefined ? null : ( + + ) + ) : ( <>