Skip to content

Open PDFs in the file viewer and add Explorer open items for the default app and a browser pane - #107

Merged
yansfil merged 9 commits into
mainfrom
prd/file-viewer-adapters
Sep 19, 2026
Merged

yansfil merged 9 commits into
mainfrom
prd/file-viewer-adapters

Conversation

@yansfil

@yansfil yansfil commented Sep 19, 2026

Copy link
Copy Markdown
Contributor

Summary

  • The core now decides a document's kind when a file opens (document_kind: text, markdown, image, pdf, binary) and the shell picks the viewer from that verdict instead of guessing from the extension in SwiftUI. A PDF is recognised by its %PDF- signature whatever its name; a file that is not UTF-8 is binary and shows "Preview only" with "This file type cannot be shown as text."; drafts and saves are refused for every non-editable kind.
  • A PDF opens in PDFKit's view (continuous vertical pages fitted to the width, text selectable) under the same document toolbar: breadcrumb, Find disabled with "Find is unavailable for PDF", Reveal in Explorer, Reveal in Finder. Wrap, the Markdown mode group and Unsaved never appear for a PDF. A PDF that cannot be read, decoded or is password-protected shows "PDF unavailable" with the reason.
  • Explorer file rows gain two items between the creations and Reveal in Finder: "Open with Default App" (macOS, through the existing external opener) and "Open in Browser Pane" (the bundled browser-pane.mjs host, the file as a file:// URL, split right of the focused pane without focus). Folder rows, the empty area and remote trees are unchanged.
  • The browser pane host accepts file:// URLs (absolute local path, no host) and profiles now lists each managed profile with running and state_modified_at; the shell picks the most recently used running profile, reuses the pane for the same file through a path-derived --key, disables the item with the reason as tooltip ("Remote files open on their device", "Opening…", "Node.js is not on PATH", "Not connected to Herdr", "No focused pane to open beside"), and shows the host's own sentence or "Browser pane did not open in time" (30 s) as the notice.
  • DESIGN.md, docs/BROWSER_PANES.md and docs/README.md describe the kinds, the menu and the shell entrypoint; design/hide.pen gains Screen / Editor / Document kinds and Screen / Panel / Explorer file menu.

Related

  • PRD: agents/prd/file-viewer-adapters/prd.md (B1-B16, D-01..D-12)
  • Sibling run on markdown-live-preview touches EditorViewerOverlay.swift and files.rs in another worktree; this diff keeps its edits to the kind switch and the toolbar visibility so the two merge cleanly.

Review focus

  • 사람이 판단할 것:
    • D-06 profile choice: the shell picks the most recently used running chromux profile without asking (the invocation said "우선 가장 최근 profile로 우선하고 나중에 고치게 하자"). A profile picker is deliberately not built.
    • Copy: the five disabled-reason tooltips and the three notices are the PRD strings verbatim; the added fourth reason "No focused pane to open beside" is not in the PRD (a pane is needed as --target-pane; the alternative was a silent failure).
    • The binding key is file- + 32 hex of SHA-256 of the standardized path (D-07 says "the file's key"; the host's identifier rule is [A-Za-z0-9][A-Za-z0-9._-]{0,79}, so a raw path cannot be the key).
    • A paused profile fails inside the pane after the host created it, so the notice is the host's sentence "Browser pane w1:p3: chromux failed (1). Inspect its host pane for diagnostics." and the failed pane stays; the PRD lists the paused profile under "host fails" and this is how the host reports it.
  • 위험한 파일:
    • herdr-core/src/files.rs: the kind decision runs in open and reads 5 bytes before the full read; update_draft/save now refuse non-editable kinds. The "Binary files are preview-only" reason is gone (the kind carries it).
    • macos/Sources/HerdrMacOS/BrowserPaneOpener.swift: a child process per request with pipes drained on background threads, one 30 s deadline across profiles + open, termination on timeout, completion exactly once on the main actor.
    • macos/Sources/HerdrMacOS/PDFDocumentView.swift: the file read is detached; PDFDocument is not Sendable so decoding stays on the main actor; updateNSView replaces the document only for a new identity so a snapshot redraw does not reset scroll.
  • 리뷰어에게 묻는 것: should a paused profile be filtered out before the open (the host would need chromux ps semantics the shell does not have today), or is the in-pane failure acceptable as shipped?

Risk surface

  • Runtime mutex: nothing new under Mutex<Runtime>; the PDF bytes are read by the shell off the main thread, the host process runs from the shell, the core reads 5 bytes and the file it already read.
  • Snapshot wire: editor.document.document_kind rides the existing revisioned editor document (a string enum); the shell decodes it in CoreBridgeEditorSnapshot.swift.
  • Ownership: the browser pane is Herdr's, created by the host through herdr plugin pane open with --no-focus; the shell only detects reuse from the snapshot (.browser(binding) with the same bindingID) before calling the host. The core keeps the editor tab and document; the shell holds the in-flight set per file path only.
  • Herdr contract: no new method; the host uses the same plugin pane open and pane report-metadata as before.
  • Failure path: every refusal is a notice with the host's or the shell's sentence; a timeout ends the child and reports "Browser pane did not open in time"; a PDF failure is the empty state with its reason; a non-UTF-8 file is "Preview only". Traces: explorer.browser_pane.opening/opened/reused/failed.
  • High-frequency path: none touched; one child process per menu choice, bounded by the in-flight set (one per file) and the 30 s deadline.

Evidence

  • 확인한 것 (dev build of this head, isolated Herdr 0.9.1 server, fixture repo with report.pdf, report-no-extension, broken.pdf, blob.bin, main.rs, README.md, index.html, shot.png; 26 registered artifacts in the local run directory):
    • B1: report.pdf and the extensionless copy open as continuous fitted pages; double-click selects a word; scrolling reaches page 3; toolbar = breadcrumb, disabled Find, both reveals.
    • B2: the PDF tab sits in the strip, switching to main.rs and back, ⌘W, and reopening from the Explorer behave like a text tab; no Unsaved.
    • B3: broken.pdf shows "PDF unavailable / PDFKit could not decode this file." under the toolbar.
    • B4: image, text and markdown open as before; blob.bin shows "Preview only / This file type cannot be shown as text."; the image toolbar now stays at the top.
    • B5: file row menu in the PRD order; folder row menu unchanged.
    • B6: "Open with Default App" on report.pdf launched Preview with the file (quit afterwards).
    • B7: double-click on index.html opens the source editor.
    • B8/B10: with hide-headless running, a Browser pane opened right of the focused terminal, focus stayed, header "Browser · hide-headless", page rendered from file://.
    • B9: choosing again left one pane (herdr pane list: w1:p1, w1:p2).
    • B11: with no running profile the exact notice showed and no pane was created.
    • B13: the bundled host against the operator server answered hide.browser is linked to another installation. Unlink it explicitly before using this build. (exit 1, nothing mutated); a paused profile surfaced the host's sentence in the notice with the other panes intact.
    • B15: node --test plugins/browser/browser-pane.test.mjs 9 pass; B16: node scripts/check-design-contract.mjs passes and the two boards render in pen.
    • Gates: verify-cargo.sh lint, verify-cargo.sh test, verify-swift.sh test (443 tests), every CONTRIBUTING check script, check-core-bridge-structure.py, the script suite, pin and schema-only contract checks.
  • 확인하지 못한 것과 그 이유:
    • B12 (node missing, not connected) and B14 (Opening… while a request is in flight) are covered by WorkspaceOutlinePresentationTests and BrowserPaneOpenerTests only; the dev machine has node on PATH and the request completes in under a second.
    • B13's 30 s timeout is proven with a real /bin/sleep child at a 1 s deadline in BrowserPaneOpenerTests, not with a stalled host.
    • B6's macOS refusal notice ("macOS could not open : ") was not provoked live.
    • The linked-elsewhere refusal was observed through the CLI, not through the shell menu, because the dev build must not join the operator's server.
  • 화면 증거: the screenshots show the workstation's home directory in breadcrumbs and terminal titles, so they stay in the local run directory (agents/runs/file-viewer-adapters/evidence/live/) and are listed in the verification report by name and observation; none is attached to this public PR.

Deterministic verification

  • Status: PASS (verification-report.json, generated 2026-09-19T03:42:01.115Z, rerun after rebasing onto 1f3bf3b)
  • PRD SHA 8f6b9073df447a8bdc5b2bb400d6808876ce156410258eb23097fdbe040d61a4, base 1f3bf3b (origin/main), head 7a448ea9, source fingerprint 94bc5686…62276
  • S1 GREEN bash scripts/verify-cargo.sh test, S2 GREEN bash scripts/verify-swift.sh test, S3 GREEN bash scripts/verify-cargo.sh lint

Agent review

  • Availability: Fidelity review completed; Code review completed (both native subagents against head 16d497dc, read-only; both confirmed the change set is byte-identical after the rebase and hold for 7a448ea9).
  • Fix now: none from either reviewer.
  • Follow-up improvements (advisory, not in this PR):
    • herdr-core/src/files.rs (Code): the > 2 MB branch hardcodes document_kind: Text, so an oversized .md loses its Markdown kind and the Preview/Edit group; contents are None there anyway, so nothing renders differently today. Compute the kind from language once and reuse it in both branches, with a test.
    • BrowserPaneOpener.selectProfile (Fidelity): a non-null but unparseable state_modified_at ranks as .distantPast rather than being excused; the host only emits ISO 8601 or null, so unreachable today.
    • BrowserPaneOpener.hostFailure (Code): only the last stderr line is parsed as JSON; the host always prints single-line JSON, worth a comment naming the assumption.
    • plugins/browser/browser-pane.mjs (Code): profiles and entries are now alphabetical and the tests lock that order in.
    • WorkspaceOutlinePresentation (Fidelity): "No focused pane to open beside" is not a PRD string; it is documented in docs/BROWSER_PANES.md and covers the connected-but-unfocused case.

AI tooling

  • 사람이 직접 작성 - [ ] 일부를 AI 도구로 작성 - [x] 대부분을 AI 도구로 작성

손으로 확인한 것: every behavior above was exercised on the running dev build and read from screenshots and herdr pane list; the PRD strings were compared against the code by grep.

files::open classifies each opened file as text, markdown, image, pdf or
binary and carries that on the editor document snapshot. A PDF is recognised
by its signature rather than its name, so it opens with any extension and is
never read whole to find out; images keep the extension set the shell used
to hold. readonly_reason now names only a size or permission reason, and a
non-text kind refuses drafts and saves on its own.
EditorViewerOverlay switches on the snapshot's document_kind instead of
inspecting extensions itself. A PDF is drawn by PDFKit's view, continuous and
fitted to the width, with the Find control disabled and saying why and the
Wrap control hidden; a file PDFKit cannot decode, cannot read, or cannot
open without a password shows the reason. Binary files keep their preview-only
state and images, text and Markdown draw as before.
…les run

browser-pane.mjs open accepts a host-less file:// URL beside http(s) and
about:blank, so a shell can show a local document in a pane. The profiles
command keeps its plain name list and adds entries carrying each managed
profile's running state, read from chromux's .state file, and that file's
modification time.
… rows

A file row's context menu gains the two open items between creation and
Reveal in Finder; folder rows, the empty area and remote trees are unchanged.
Open with Default App hands the file to macOS through the existing external
opener and shows its refusal as a notice. Open in Browser Pane runs the
bundled browser-pane host with the login PATH's node, choosing the most
recently started running chromux profile, splitting right of the focused
pane without moving focus, and reusing the pane already bound to the file.
The item is disabled with one reason as its tooltip when node, the Herdr
connection, or a focused pane is missing, or while the same file is still
opening; a host refusal is shown verbatim and a request past 30 seconds is
ended and reported.
@yansfil
yansfil merged commit 34336b1 into main Sep 19, 2026
5 checks passed
@yansfil
yansfil deleted the prd/file-viewer-adapters branch September 19, 2026 03:51
yansfil added a commit that referenced this pull request Sep 19, 2026
## Summary

Explorer에서 파일을 한 번 클릭할 때마다 영구 탭이 쌓이던 것을 VS Code의 preview tab 모델로 바꿉니다: 한
번 클릭은 체크아웃당 하나뿐인 교체형 preview 탭을 열고, 더블클릭·첫 편집·Keep Open·드래그가 그 탭을 영구 탭으로
승격하며, dirty 탭은 어떤 경우에도 교체되지 않습니다.

- 코어(`herdr-core`)가 preview 여부를 소유합니다. `EditorTabSnapshot.preview`와 스트립
항목 `StripTabSnapshot.preview`가 추가됐고, `file_open`/`changes_select` 페이로드는
`preview: bool`(기본 false)을 받으며, 승격은 새 이벤트 `file_keep_open` 하나로 옵니다.
교체·승격·dirty 검사·슬롯 상속·Recent Closed 제외는 모두 `runtime/editor.rs`의
`place_editor_tab`/`promote_editor_tab`/`retire_editor_tab` 안에서만 결정됩니다.
- 교체는 제자리에서 일어납니다: 새 preview 탭은 이전 preview 탭의 `checkout_tab_order` 슬롯과
진행 중인 `pending_tab_move.desired` 항목을 물려받고, 교체된 탭의 문서·history·Changes 선택은
`retire_editor_tab`이 정리합니다(`close_file_tab_now`도 같은 함수를 씁니다). 교체된
preview는 Recent Closed에 남지 않습니다.
- 승격 트리거: Explorer 더블클릭(`NSOutlineView.doubleAction`), 탭 제목
더블클릭(`TapGesture(count: 2)`), 첫 draft 변경(`FileDraft`가 `dirty`로 바뀌는 프레임),
메뉴 `File > Keep Open`(⇧⌘K, 터미널 포커스에서도 잡히도록 `KeepOpenShortcutPolicy`가 로컬
키 모니터에 붙습니다), 탭 드래그 순서 변경(`reorder_tab`의 로컬 커밋 분기).
- 셸은 preview 탭 제목을 기울임꼴로 그리고 툴팁·접근성 라벨에 "· Preview"를 붙입니다. 번들된 Inter에는
italic 축이 없어 `HideTheme.Typography.previewSlant`(12°)로 CoreText 폰트 행렬을
기울인 합성 oblique를 씁니다. 색·닫기 버튼·keycap은 일반 탭과 같습니다.
- Explorer 한 번 클릭과 Changes 행 한 번 클릭만 preview를 요청합니다. Cmd+P, Recent
Closed 재열기, `reveal_path`, 새 파일 생성, Explorer Return은 영구 탭으로 엽니다.
- `design/hide.pen`에 `Screen / Workbench / Preview tab`
보드(preview·promoted·dirty kept 세 상태)를 먼저 그렸고, `--text-preview-slant`를
`scripts/pen-token-map.json`에 매핑했습니다. `DESIGN.md`에 "Editor preview tab"
절, `docs/README.md`에 라우팅 행을 추가했습니다.

## Related

- PRD: `agents/prd/editor-preview-tab/prd.md` (B1-B20, D-01..D-14)
- origin/main `34336b1` (#107)을 머지해 두 충돌(`design/hide.pen`,
`docs/README.md`)을 양쪽 보존으로 풀었습니다.

## Review focus

- **사람이 판단할 것**: (1) PRD가 가정으로 남긴 것들의 제품 해석 - Keep Open 단축키를 ⇧⌘K로 둔
것(`ShellMenuCommand.keepOpen`), Explorer Return이 영구 탭으로 여는 것, 이미 열린
preview diff에 대한 비-preview `changes_select`가 승격으로 읽히는 것, 기존 내용과 같은 draft
echo가 승격하지 않는 것. (2) 합성 12° oblique의 시각적 무게가 SF Mono 없는 환경에서
적절한지(`HideTheme.Typography.previewSlant`). (3) B8의 "옆에 연다": dirty
preview가 스트립 끝이 아니면 새 preview는 기존 "새 탭은 끝에" 규칙대로 스트립 끝에 붙습니다. 리뷰어가 문구를 더
엄격히 읽는다면 후속으로 다룹니다.
- **위험한 파일**: `herdr-core/src/runtime/editor.rs`의 `place_editor_tab` -
스트립 슬롯 상속을 위해 모든 체크아웃의 `checkout_tab_order`/`pending_tab_move`를 문자열 치환으로
돕니다(탭 id가 `workspace:checkout`을 포함하므로 다른 체크아웃과 겹치지 않습니다).
`macos/Sources/HerdrMacOS/HerdrApp.swift`의 로컬 키 모니터 분기 - 이벤트를
삼키므로(`return nil`) SwiftUI 메뉴 단축키와 두 번 발화하지 않습니다(Reopen Closed Tab과 같은
구조). `CoreBridgeEditorSnapshot.swift`의 `preview` 키는 필수 키입니다(`dirty`와
같음); 코어가 `editor` 섹션을 통째로 다시 보내므로 항상 실립니다.
- **리뷰어에게 묻는 것**: ⇧⌘K가 Keep Open으로 적절한지, 아니면 다른 키를 원하는지.

## Risk surface

- **Runtime mutex**: `Mutex<Runtime>` 안에서 추가된 일은 벡터 재배열과 `BTreeMap` 문자열
치환뿐입니다. 서브프로세스·블로킹 I/O·직렬화 없음.
- **Snapshot wire**: `editor` 섹션(revisioned `rest`)과 스트립 항목에 `preview:
bool`이 추가됩니다. `EditorTabSnapshot`/`StripTabSnapshot`은 `PartialEq`이라 플래그
반전이 델타로 발행됩니다.
- **Ownership**: 코어 소유(visible tab)만 건드립니다. 교체된 preview 탭이 활성 탭이었으면 새 탭이
활성 탭이 되고, Herdr에는 기존과 같이 사후 통지됩니다. Herdr 소유 값은 변경 없음.
- **Herdr contract**: 새 메서드·필드 없음.
- **Failure path**: `file_keep_open`이 모르는 탭을 가리키면
`editor.keep_open_unknown_tab` 오류로 `last_error`에 기록됩니다. 교체·dirty 보존·승격은
`editor.preview_replaced`/`editor.preview_kept_dirty`/`editor.preview_promoted`
진단으로 남습니다.

## Evidence

- **확인한 것**: `bash scripts/verify-cargo.sh test`(Rust 전체 suite + 새
`runtime/tests/editor_preview.rs` 11개: B1/B2/B14/B20, B3, B4, B5, B6,
B7, B8, B9/B10, B12, B13/B15, D-09), `bash scripts/verify-swift.sh
test`(새 `EditorPreviewTabPresentationTests` 6개: 스트립 플래그, spoken/italic
프레젠테이션, 디코드 기본값, CoreText 행렬 `c == tan(previewSlant)`, ⇧⌘K 정책, 포커스 무관
응답), `bash scripts/verify-cargo.sh lint`가 헤드 `07761b4`에서 모두 exit 0 (sasu
verify PASS, 38.5 s / 10.1 s / 1.3 s). `node
scripts/check-design-contract.mjs`(gen-pen/check-pen 포함),
`check-shortcut-contract`, `check-right-panel-sections`,
`check-core-bridge-structure`, `check-capability-readers-off-lock`,
`check-no-workstation-identity`, `check-no-attribution` 통과.
네이티브: `macos/scripts/build_dev_app.sh`로 만든 후보 번들을 격리된 Herdr 0.9.1
서버(`HERDR_SESSION=eptab-qa`, 전용 `HERDR_SOCKET_PATH`, 격리 XDG/config,
fixture 저장소 하나)에 붙여 peekaboo로 정확한 창 하나만 잡고 확인했습니다. 8d505d2 번들에서 B1(한 번
클릭 → 기울임꼴 탭), B2/B14/B20(두 번째 파일이 같은 슬롯을 물려받고 탭 수 불변, Explorer 선택 이동),
B4(Explorer 더블클릭 → 같은 슬롯에서 정체), B5 형태(승격 뒤 한 번 클릭 → 옆에 새 preview),
B16(접근성 라벨 "README.md · Preview"), B12(Changes 한 번 클릭 → 같은 슬롯의 diff
preview), B6(탭 제목 더블클릭 → 승격). 07761b4 번들에서 B1과 `File > Keep Open` 메뉴
승격(스트립 `README.md · Preview` → `README.md`). 운영 중인 hide.app과 그 서버는 건드리지
않았습니다.
- **확인하지 못한 것과 그 이유**: ⇧⌘K 키 입력 자체는 네이티브로 확인하지 못했습니다. peekaboo의 합성 키 입력은
이 QA 구성에서 앱에 닿지 않았고(기존 ⌘W도 같은 방식으로 아무 효과가 없었음), 메뉴 경로와
`keepOpenChordIsAnsweredRegardlessOfFocus` 단위 테스트만 확인했습니다. B7(드래그 승격),
B8(dirty 보존), B3(체크아웃별 슬롯)은 Rust 테스트로만 고정했고 네이티브로 드래그하지 않았습니다. 리뷰어가
설치본에서 ⇧⌘K를 한 번 눌러 봐 주시면 그 공백이 닫힙니다.
- **화면 증거**: 이 저장소 규칙(`AGENTS.md` "Evidence Belongs Outside The
Repository")에 따라 스크린샷은 커밋하지 않고 로컬 run 디렉터리
`agents/runs/editor-preview-tab/native/01-preview-readme.png` …
`09-keep-open-menu-promotes.png`(sha256은 verification-report.json에 등록)와
설계 보드 `design/pvt-board.png`에 있습니다. 위 "확인한 것"에 각 장면이 무엇을 보여주는지 적었습니다.

## AI tooling

- [ ] 사람이 직접 작성  - [ ] 일부를 AI 도구로 작성  - [x] 대부분을 AI 도구로 작성

**손으로 확인한 것**: 네이티브 스크린샷 9장을 열어 각 장면이 PRD 행과 일치하는지 대조했고, 설계 보드 export를
`DESIGN.md`의 토큰과 대조했습니다. Fidelity와 Code 리뷰(둘 다 07761b4)는 아래에 정리했습니다.

## Product And Scope Result

- PRD: `agents/prd/editor-preview-tab/prd.md`
- Implementation state: `agents/runs/editor-preview-tab/state.json`
(record tree, local)
- Verification report:
`agents/runs/editor-preview-tab/verification-report.json` (status:
PASS), summary `verification-report.md`

## Actual Tests

- S1: GREEN - `bash scripts/verify-cargo.sh test` (cwd: ., exit 0)
- S2: GREEN - `bash scripts/verify-swift.sh test` (cwd: ., exit 0)
- S3: GREEN - `bash scripts/verify-cargo.sh lint` (cwd: ., exit 0)

## Actual Observations

- `native/01-preview-readme.png` (sha256 040676a3…): B1/D-06, 8d505d2
번들, 2026-09-19T04:13Z.
- `native/02-replaced-second.png` (sha256 2e9c980d…): B2/B14/B20.
- `native/03-promoted-second.png` (sha256 1b56639d…): B4.
- `native/04-preview-beside-promoted.png` (sha256 a333d0ea…): B5 형태 +
B16 접근성 라벨.
- `native/06-diff-preview-shares-slot.png` (sha256 014f0436…): B12/D-02.
- `native/07-title-double-click-promotes.png` (sha256 be1df87e…): B6.
- `design/pvt-board.png` (sha256 71f71374…): D-13 보드 export.
- `native/08-merged-head-preview.png` (sha256 88807187…): 07761b4 번들,
B1.
- `native/09-keep-open-menu-promotes.png` (sha256 20c8c19b…): 07761b4
번들, `File > Keep Open` 메뉴 승격; 합성 ⇧⌘K는 앱에 닿지 않음(⌘W도 동일).

## Deterministic Verification

- Deterministic verification: PASS
- PRD SHA:
e3bda1e05fb7d4f7196569f2570131e1d22f5157d671e0c2574638e83c3c245d
- Base SHA: bae82c4ad8691483228a340491fa22ecd82bc885
- Head SHA: 07761b4
- Source fingerprint:
934eb5f1c6fca5da91a5116b9cd27446278f20b6a075a0be1a76d34f538da955
- Generated: 2026-09-19T04:27:59.231Z
- Agent reviews are visible advisory notes produced by native runtime
subagents.

## Agent Review: Fix Now

None. Fidelity 리뷰가 aba6c10에서 낸 한 건(⇧⌘K가 SwiftUI 메뉴 단축키로만 있어 터미널 포커스에서
죽는다)은 07761b4에서 `KeepOpenShortcutPolicy` + 로컬 키 모니터 분기 +
`keepOpenChordIsAnsweredRegardlessOfFocus`로 고쳤고, 두 리뷰 모두 07761b4에서 Fix
now 없음으로 재판정했습니다.

## Agent Review: Follow-up Improvements

- B8 "옆에 연다"는 dirty preview가 스트립 끝이 아닐 때 문자 그대로 인접하지 않고 스트립 끝에 붙습니다(기존
`ordered_strip`의 "새 항목은 끝" 규칙). 문서에 한 줄 적거나 인접 삽입으로 바꿀지 결정 필요.
- B17(색·닫기 버튼·keycap이 일반 탭과 같음)은 구조상 참이지만 회귀 테스트가 없습니다.
- `close_file_tab_now`가 `was_active`를 `retire_editor_tab`과 중복 계산합니다;
`retire_editor_tab`이 `(tab, was_active)`를 돌려주면 정리됩니다.
- `place_editor_tab`의 전 체크아웃 `checkout_tab_order` 치환 루프가 탭 id에
`workspace:checkout`이 포함돼 안전하다는 불변식을 주석으로 남기면 좋습니다.

## Delivery Staging

- Mode: pr
- Branch: prd/editor-preview-tab
- Base: main

## Changed Paths In This PR

`git diff --stat origin/main...HEAD`, 27 files: `DESIGN.md`,
`agents/prd/editor-preview-tab/prd.md`, `design/hide.pen`,
`docs/README.md`, `herdr-core/src/model.rs`,
`herdr-core/src/runtime/{editor,events,session}.rs`,
`herdr-core/src/runtime/tests.rs`,
`herdr-core/src/runtime/tests/{editor_preview,editor_reopen}.rs`,
`macos/Sources/HerdrMacOS/{CoreBridge,CoreBridgeEditorSnapshot,CoreBridgeWorkspaceSnapshot,HerdrApp,HideEnvironment,HideMainView,HideTheme,RightPanel,ShellMenuCommand,ShellModel,ShellModelNavigation,WorkspaceOutlineView}.swift`,
`macos/Tests/HerdrMacOSTests/{EditorPreviewTabPresentationTests,RightPanelPresentationTests,WorkspaceOutlineEditingTests}.swift`,
`scripts/pen-token-map.json`.

## Risks, Rollback, And Human Review

- 되돌리기: 이 PR을 revert하면 됩니다. 영속 상태·설정·설치 경로 변경이 없습니다.
- 남은 사람 확인: 설치본에서 ⇧⌘K 한 번(위 "확인하지 못한 것"), 합성 oblique의 시각 무게, B8 인접성 해석.
- 실행하지 않은 것: 없음. CI(`verify`, `design-contract`)는 PR에서 돌아갑니다.
yansfil added a commit that referenced this pull request Sep 19, 2026
…#110)

## Summary

- A Markdown file now opens in a **Live** editor: one editable
`NSTextView` whose text storage is the source, with headings, bold,
italic, strikethrough, inline code, fenced code blocks, lists, quotes,
links and thematic breaks drawn in place and their markup glyphs hidden
by an `NSLayoutManager` subclass. The caret line and every line a
selection touches show the raw markup; the rest stays formatted. The
read-only Preview mode (`MarkdownPreview.swift`,
`MarkdownDocumentTests`) is gone; the toolbar group is "Live / Source"
and the core's per-tab field is `markdown_live` (runtime only, a
reopened tab starts Live).
- Parsing uses Foundation's `AttributedString(markdown:)` with source
positions (`MarkdownLiveSource.plan(for:)`), runs off the main thread
once per change with pending changes coalesced, and applies attributes
on the main thread without touching the string. A file over 256 KB opens
in Source with both mode buttons disabled and the notice "Live preview
is off for files over 256 KB". A parse failure keeps the source
monospaced, puts the reason in the notice and does not block input.
- List editing rules (PRD amendment 1, D-14, ported from orca's rules,
not its code): Enter continues a `- ` / `n. ` item, Enter on an empty
item clears the marker and renumbers below, Tab and Shift-Tab move one
level (two spaces) with renumbering, Backspace on an empty item removes
the marker only, a lone `1. ` line stays as typed, and none of it runs
during a Korean composition. `MarkdownListEditing` is pure functions
over the text; `MarkdownListKeys` wires them into the Live text view
and, only for Markdown, into the Source editor (`CodeEditorTextView`).
- Draft, autosave, "Unsaved", conflict banner, Find and text-scale chord
are the Source editor's existing paths; nothing in the Live view has its
own authority. Cmd-click on a link goes through `openDocumentLink`
(http(s) external, checkout-relative files revealed, otherwise the
existing notice); a plain click places the caret.
- Assistant-turn rendering that shared `MarkdownPreview.swift` moved to
`ConversationMarkdown.swift` unchanged in behavior. `DESIGN.md`
describes the two modes and the list rules; `design/hide.pen` gains
`Screen / Editor / Markdown live` (formatted, caret line, code block,
empty document, over 256 KB) on eight new tokens
(`Editor.headingFontSizes`, `Editor.quoteRuleWidth`,
`Editor.italicSkew`) added to `HideTheme`.
- Two suite fixes that surfaced while shipping, not Markdown-specific:
the vendored Highlightr batches its per-run `setAttributes` inside
`stringStorage.beginEditing/endEditing` (each run was running
`processEditing` over the whole document, seconds on a few hundred KB),
and `FileDocumentStateTests` polls for the autosave instead of sleeping
a fixed 700 ms past a 450 ms debounce.

## Related

- PRD: `agents/prd/markdown-live-preview/prd.md` (B1-B22, D-01..D-14;
amendment 1 added B16-B22 and D-14)
- Merged twice with `main` during the run: PR #107 (document kinds,
`EditorViewerOverlay.swift` kind switch) and PR #108 (editor preview
tab). The Explorer, preview-slot and `files.rs` code is byte-identical
to `main`.

## Breaking change

- The editor tab snapshot field `markdown_preview` is renamed
`markdown_live` and the `file_view` event payload with it. The value was
never persisted (per tab, runtime only), so no state directory or saved
setting changes; a shell and core are always built together from this
tree.

## Review focus

- **사람이 판단할 것**:
- D-04 reveal rule: markup shows on the caret line and on every line a
selection touches, and a fenced code block reveals as a whole block when
the caret is inside it. Obsidian's behavior was the assumption.
- The Live view is always wrapped at the 720 pt reading measure with no
line-number ruler; Wrap and the ruler exist only in Source (D-05).
- D-06 outcome: Foundation's parser gave exact source ranges for every
D-03 item, so `apple/swift-markdown` was **not** vendored. One quirk
handled in `MarkdownLiveSource`: after a multi-line code span Foundation
keeps reporting the same line number while the byte offsets stay right,
so the plan builder trusts offsets, not lines.
- List rules chosen where the PRD left room: a sole top-level empty
ordered item on Enter is kept as text (B20) while any other empty item
clears its marker (B17); Shift-Tab at indent 0 consumes the key and
changes nothing; task boxes (`- [ ]`) are not treated as list items so
they stay raw source (B6).
- `HighlightedCodeEditor` gained `markdownListEditing` so Source mode of
a Markdown file follows the same keys (B22); other languages are
untouched.
- **위험한 파일**:
- `macos/Sources/HerdrMacOS/MarkdownLiveEditor.swift`: the text view is
rich text (`isRichText = true`) with `readablePasteboardTypes =
[.string]`; a plain-text `NSTextView` applies typing attributes to the
whole storage after an edit, which rewrote the document in the H1 font
once during native QA and is now pinned by
`editingInsideAHeadingLeavesTheBodyAtItsOwnSize` and
`pastingRichTextBringsOnlyItsCharacters`. The parse is versioned so a
stale result never applies, and a result arriving during an IME
composition is dropped and re-parsed on commit.
- `macos/Sources/HerdrMacOS/MarkdownLiveSource.swift`: the span/marker
plan built from Foundation's source positions (1-based lines, UTF-8 byte
columns) mapped to UTF-16 ranges; thematic breaks carry their newline so
the hairline draws from the paragraph's first glyph.
- `macos/Sources/HerdrMacOS/MarkdownListEditing.swift`: the renumbering
column logic (`renumber(_:column:around:)`) bounded by shallower items
and blank lines, and `Context.init`, which reads the caret line through
`NSString` and carries a CRLF line's `\r` into every rewritten line (the
Code review found the first version dropping a character on CRLF files;
fixed in `17058c5` with tests).
- `macos/Vendor/Highlightr/src/classes/CodeAttributedString.swift`: five
lines in vendored code; the outer `beginEditing` was already there, the
inner storage's was not.
- **리뷰어에게 묻는 것**: on this merged head, Explorer rows clicked through
synthesized events (single, double, row body) highlighted the row but
opened nothing, while ⌘P opened the same files; the Explorer code is
`main`'s from PR #108. Does a physical single click open a preview tab
on `main` for you? If not, that is #108's, not this branch's, but it is
worth knowing before both land.

## Risk surface

- **Runtime mutex**: nothing new under `Mutex<Runtime>`; the core change
is the field rename. Parsing and styling live in the shell.
- **Snapshot wire**: `editor.tabs[].markdown_live` rides the existing
revisioned editor tab record where `markdown_preview` rode; the
`file_view` event carries `{tab_id, markdown_live, wrap}`.
- **Ownership**: the core owns the mode per tab and the shell dispatches
`file_view` when the user changes it; the Live view reads the draft and
writes it back through the same `updateDraft`/`scheduleFileSave` path as
Source, and holds no mirrored state.
- **Herdr contract**: no method or field beyond the schema; Herdr is not
involved.
- **Failure path**: a parse failure is the notice with
`localizedDescription` under the toolbar and the source stays monospaced
and editable; an over-limit file is the fixed notice with both mode
buttons disabled; a link that cannot open is the existing
`openDocumentLink` notice. Nothing is logged for a parse failure beyond
the notice, because it is per keystroke and recoverable.
- **High-frequency path**: per keystroke the Live view does one
text-storage edit, one `plan(for:)` on a worker thread (coalesced: at
most one in flight and one pending), one attribute restyle of the
changed region and one hidden-marker refresh on the main thread.
Measured on a 10,000-line / 224,706-byte document in the debug build
(`agents/runs/markdown-live-preview/perf/REPORT.md`, 60 keystrokes with
a caret move each): main-thread insert p50 6.6 ms / p95 10.6 ms / max
16.8 ms, caret move p50 4.7 ms / p95 4.9 ms, changed-region apply p50
5.9 ms, keystroke-to-formatted p50 238 ms (parse-bound; `-O` parse is
~65 ms). Physical footprint peak stays at the process baseline (377 MB)
across the burst; before the fixes in `37ca71f` and `5c55a3a` an insert
cost 57 ms p50 and sixty keystrokes grew the process by a gigabyte.
Native: idle 1.4% CPU with the document open, 125% CPU during the driven
burst. Regression owners: `MarkdownLiveEditorTests` (formatting, reveal,
IME, paste, list keys) and `MarkdownLiveSourceTests` (plan ranges), plus
the threshold recorded in the report (insert and caret p95 under 16 ms
at 10,000 lines, flat footprint).

## Evidence

- **확인한 것** (dev bundles of `b45a67d`, `1bdce49`, `eb14476` and
`c9e36b6`, isolated Herdr 0.9.1 server, fixture with notes.md,
README.md, empty.md, big.md 300 KB, long.md 10,000 lines; 39 registered
artifacts in the local run directory, fonts read through
`AXAttributedStringForRange`, text and caret through AX, key semantics
through CGEvents with the app frontmost):
- B1/B5/B6: notes.md opens Live with the "Live / Source" group; H1
SemiBold 28, H2 SemiBold 24, body Inter 15, bold Inter-Bold, inline code
monospaced 12 with the backticks hidden, `•` bullets and numbers with
indent, the quote rule, the `---` hairline, and the table, task box and
image kept as monospaced source.
- B2/B3/B4: the caret line reveals `# `, `**`, backticks and fences
(inside a block the whole block reveals; outside, the fence lines
collapse); typing Korean and English mid-line lands at the caret and the
neighbouring lines stay formatted; Source shows the typed source
verbatim; every typed character reached the file through autosave.
- B7: a plain click on a link placed the caret; Cmd-click on
`./README.md` switched to the README tab; Cmd-click on `./nope.md`
showed "The linked file is missing or outside this checkout."
- B8: Source shows the ruler, Wrap and the monospaced font; ⌘= twice
scaled the Live body 15 → 18 pt and the heading 28 → 33.6 pt, ⌘0
restored.
- B9: empty.md opens as an empty Live view and a typed heading and
italic render.
- B10: big.md opens Source with both mode buttons disabled and the
notice (also on both merged heads).
- B11: README opened Live in its own tab while notes.md kept Source; a
reopened tab starts Live.
- B13: the numbers above; `long.md` open and 60-keystroke burst in the
native app sampled idle and driven.
- B16-B20, B22: real Return/Tab/Shift-Tab/Delete events in Live and
Source on `- one` and `1. one` lists produced the PRD's outcomes and the
saved file is plain Markdown (bytes checked with `od`); CRLF documents
are covered by `crlfLinesKeepTheirEndingsAndEveryCharacter` (value
tests), not driven live.
- B14/B15: no `markdown_preview`, `MarkdownPreview.swift` or
`MarkdownDocumentTests` in the tree; `node
scripts/check-design-contract.mjs`, `gen-pen`/`check-pen` pass with the
board present.
- Gates at `310b29a`: `verify-cargo.sh test` 786 passed,
`verify-swift.sh test` 484 passed (4.2 s), `verify-cargo.sh lint`, every
CONTRIBUTING check script that runs unattended (design contract, pin
single source, schema-only contract, no-attribution,
no-workstation-identity, core-bridge structure, typed contract
`generated`/`structure`, and the rest), `check-hide-copy.mjs` against
`0a138f9`: the only inventory change is `markdown-preview` →
`markdown-live` plus `markdown-live-unavailable` (accessibility
identifiers).
- **확인하지 못한 것과 그 이유**:
- B12 (parse failure notice) only in the hosted test
`aFailedParseLeavesTheSourceMonospacedWithTheReason`; Foundation's
parser did not fail on any fixture, so it was injected.
- B21 (composition) only in the hosted test through `setMarkedText`; a
live Korean composition was typed, but Enter/Tab during an uncommitted
composition was not driven by synthetic events.
- B7's http(s) branch was not clicked live, to avoid opening the
workstation's browser; the branch is `openDocumentLink`'s existing code.
- B13 release-build timings: the dev bundle is a debug build; only
`plan(for:)` was timed with `-O` (65 ms p50). Scrolling and selection
drag on the 10,000-line document were not measured.
- Explorer click-to-open on the `c9e36b6` bundle under synthetic input
(see the reviewer question); files were opened through ⌘P instead.
- One stray Return during native QA landed in the operator's own hide
window when it took focus between my frontmost check and the key event;
nothing in this branch was affected, noted for honesty.
- **화면 증거**: the captures show the workstation's home directory in the
terminal title and breadcrumbs, so they stay in the local run directory
(`agents/runs/markdown-live-preview/live/shots/`, indexed in `INDEX.md`,
registered in the verification report by name, sha256 and observation);
none is attached to this public PR.

## Deterministic verification

- Status: PASS
(`agents/runs/markdown-live-preview/verification-report.json`, attempt 9
at head `310b29a`, generated 2026-09-19)
- PRD SHA
`58088e7a1ed0e13a02a6807a2ea99ce5ac940d2454ed81a1d9178f317e02db68`, base
`a233c6a` (implement start), head `310b29a` (merged with `origin/main`
`0a138f9` at `c9e36b6`)
- S1 GREEN `bash scripts/verify-cargo.sh test`, S2 GREEN `bash
scripts/verify-swift.sh test`, S3 GREEN `bash scripts/verify-cargo.sh
lint`

## Agent review

- Availability: Fidelity review completed and Code review completed
(native subagents, read-only, against `1bdce49`, re-confirmed for
`f98a6e3`, `c9e36b6` and `310b29a`; both report no Fix-now item at
`310b29a`, the Fidelity reviewer moved B20 to MET on the orca citation,
and the Code reviewer reran its CRLF reproductions against the fix).
- Fix now:
- **Code review, `MarkdownListEditing.Context.init` CRLF corruption**:
`String.dropLast(2)` on a line ending in `
` dropped one Character (the CRLF grapheme) plus the last content
character, so every list key on a CRLF file lost a character and
flattened the line ending. **Fixed in `17058c5`**: the line content
comes from `NSString.getLineStart(_:end:contentsEnd:for:)`, the carriage
return is re-appended to every rewritten line, any other terminator
makes the key fall through to the text view, and
`MarkdownListEditingTests` gained CRLF and foreign-terminator cases (the
reviewer's two reproductions included).
- **Fidelity review, B20 narrower than the PRD sentence** (`1. ` kept as
text only for a sole top-level item): **kept as implemented**. D-14 rule
6 names orca's handling as the rule; orca's
`commitEmptyOrderedListMarkerAsText`
(`rich-markdown-list-continuation.ts`) applies only when the ordered
list has one item and is not nested in a list item, which is the shipped
guard. The PRD sentence summarises that rule without the qualifier; a
human may overrule by broadening the guard.
- Follow-up improvements (advisory, not in this PR):
- `MarkdownListEditing.renumber`/`belongs` walk the contiguous run of
the column on every list key (O(n) in the list's length, main thread);
fine for ordinary lists, worth a cap if very long ordered lists turn out
common (Code).
- `isSoleItem` inspects only the adjacent lines, an engineering reading
of orca's `childCount === 1` over a source text; a human with orca open
may want to confirm (Fidelity).
- The H5/H6 comment mismatch in `HideTheme` was reworded in `310b29a`;
H5 and H6 remain the same size and weight, which no requirement
distinguishes (Fidelity).

## AI tooling

- [ ] 사람이 직접 작성  - [ ] 일부를 AI 도구로 작성  - [x] 대부분을 AI 도구로 작성

**손으로 확인한 것**: the font runs, caret positions and saved bytes quoted
above were read from the running app through the accessibility API and
compared against the PRD's strings and the DESIGN.md sizes; the PR text
was checked against the diff, not the PRD's intent.
yansfil added a commit that referenced this pull request Sep 19, 2026
…ng it (#109)

## Summary

- Registered projects can be pinned from the row menu (`⋯` or
right-click): a `Pinned N` section leads the Projects list above
`Projects · Recent activity`, pinned rows keep activity order among
themselves, and a pinned project never falls into the `Inactive
projects` fold. The flag lives on `WorkspaceRegistration` and survives
relaunch; older stores load unpinned.
- `Remove project…` replaces the old refusal for a project with open
panes. The confirmation names what the close will send (`Closes 3 panes
(1 running agent).`) and the core closes those panes through Herdr,
waits for the confirmation, and only then removes the registration. A
timeout or refusal keeps the project registered with the reason in the
status banner, and the same command retries from the panes that remain.
- Removing the project that holds the focused checkout moves focus and
the pane selection to the next project, the way a Herdr restart does;
without this the shell reported `pane.projection_unavailable` on every
sync until the operator clicked elsewhere (found live, fixed in
b6d21b4).
- Section headers are rows of the one sidebar list, so pinning moves a
row in place instead of removing and reinserting it, and the list
reveals the `Pinned` header when it first appears (the two-`ForEach`
version left the list scrolled past it).
- `design/hide.pen`: `Screen / Sidebar / Projects` gains the pin-0,
`Pinned 2`, row-menu and `Remove project…` states drawn from the
existing masters; the five `Scratch /` boards that rode the branch base
are deleted. `DESIGN.md`, `docs/README.md` and
`docs/PERFORMANCE_TESTING.md` are updated with the behavior.

## Related

- PRD: `agents/prd/hide-sidebar-pinning/prd.md` (B1-B20)
- The branch base 2c3c39b was a canvas checkpoint (Overview scratch
boards) that never reached `main`; `origin/main` (#107) is merged in at
7737f0c, so the diff against `main` is the pinning and removal change
only. Those scratch boards remain on
`design/overview-scratch-2026-09-19` and tag
`backup/hide-sidebar-pinning-pre-merge`.

## Result

- A registered project can be pinned and unpinned from its row menu; a
`Pinned N` section leads the Projects list while any exist, ordered by
activity, never folded, and the flag survives relaunch.
- `Remove project…` on a project with panes confirms with the pane and
running-agent counts, closes the panes through Herdr, and removes the
registration only after Herdr confirms; the project stays registered
with the reason visible on timeout, refusal, or no live connection.
- Removing the focused project moves focus to the next project instead
of leaving a dangling selection.
- Not included (PRD non-goals): deleting files, worktrees or Herdr
workspaces; pinning a remote project or a temporary folder row; a
progress indicator while the close is in flight.

## Screenshots / Demo

No inline images: the screenshots are registered run artifacts under
`agents/runs/hide-sidebar-pinning/live/shots/` (local-only by repository
rule, see AGENTS.md "Evidence Belongs Outside The Repository"), and this
session had no channel to upload GitHub user attachments. What each
shows is written out under Evidence below and in the artifact
descriptions in `state.json`; the design target is the `Screen / Sidebar
/ Projects` board in `design/hide.pen` (states `Pinned 2`, `Row menu`,
`Remove project…`).

## Human Review Focus

- **사람이 판단할 것**: dialog copy defaults not spelled out by the PRD:
`Closes N pane(s) (M running agent(s)).` with the parenthetical omitted
at 0 running agents, `Close N pane(s) and remove`; "running" means the
agent's activity axis says `working`. Row-menu order `Pin`/`Unpin`,
divider, `Refresh GitHub status`, `New worktree…`, divider, `Remove
project…`. Pin and Remove are offered only for local registrations (a
remote project is the device's own; a temporary folder row has nothing
to store the pin in).
- **위험한 파일**: `herdr-core/src/runtime/projects.rs` (`remove_workspace`,
`ingest_workspace_close_result`, `retire_workspace_registration`: the
in-flight set and the focus hand-off),
`herdr-core/src/worktree_control.rs` (`spawn_workspace_close` reuses the
worktree close-then-confirm thread), `herdr-core/src/sidebar.rs`
(removal counts on the per-sync summary pass),
`macos/Sources/HerdrMacOS/SidebarList.swift` (`revealTopRowID` scroll).
- **리뷰어에게 묻는 것**: the focus hand-off after removing the focused project
picks the first existing checkout in list order
(`resync_navigator_focus`), which is the first pinned project when one
exists. Is that the order you want, or should it prefer the most
recently active project?

## Risk surface

- **Runtime mutex**: the pane close runs on the
`herdr-core-workspace-close` thread (same shape as worktree removal) and
re-enters the runtime once with the result; under the lock the removal
path only mutates snapshot vectors and queues the off-lock state save.
Removal counts are computed on the existing per-sync summary pass, one
pass over the checkout pane lists.
- **Ownership**: Herdr owns pane existence, so the registration is
retired only after Herdr confirms every pane is gone
(`confirmation_state` over `session.snapshot`); the pin is core-owned UI
state persisted to the app state file.
- **Herdr contract**: `pane.close` and `session.snapshot` only, both in
`contracts/herdr-api.schema.json` for the pinned v0.9.1.
- **Failure path**: a close timeout or refusal sets
`workspace.remove_failed` in the status banner ("… The project stays
registered; remove it again to close the panes that remain."); removing
with panes and no live connection sets the same kind with "needs a live
Herdr connection"; pinning an unregistered id sets
`workspace.pin_unregistered`. Every transition emits a
`workspace.pinned|unpinned|unregistered` diagnostic and
`remove.close_requested` names the pane ids.

## Evidence

- **확인한 것**: `bash scripts/verify-cargo.sh test` (561 lib tests +
workspace crates), `bash scripts/verify-swift.sh test` (448 tests),
`bash scripts/verify-cargo.sh lint`, every `check-*` lane in
CONTRIBUTING.md, `node scripts/check-design-contract.mjs` (canvas:
Screen 25, Scratch 0), `python3 -m unittest discover -s scripts/tests`
(38). Live, against a private Herdr 0.9.1 server
(`HERDR_SOCKET_PATH=/tmp/hsp/h.sock`, isolated HOME and XDG dirs, four
fixture projects: alpha with 3 panes and two long-running processes,
bravo with 1 pane, charlie 14d and delta 18d inactive) in the dev app
built by `macos/scripts/build_dev_app.sh`, input bound to that PID: pin
from the `⋯` menu and from right-click; `Pinned 1` appears and the
header is the first row after relaunch; unpin returns today's screen;
pinning the folded charlie takes it out of `Inactive projects 2` into
`Pinned 1`; two pins order alpha (18m) above charlie (14d); a pinned
row's menu says `Unpin`; `Remove project…` on alpha shows `Closes 3
panes. The folder, repository, and worktrees stay on disk.` / `Close 3
panes and remove`; after confirming, `herdr pane list` holds only
`w2:p1` and `ps` finds neither `hsp-longrun` process (PRD Risk 1: the
pane close ended the PTY and the processes in it, no survivors); `Remove
project…` on a project with no panes shows the registration-only copy;
removing the focused project lands on the next project with its pane
projected.
- **확인하지 못한 것과 그 이유**: a Herdr close timeout or refusal in the live app
(only unit-tested; the private server closed every pane within the
timeout). A remote device's project rows (no remote target in the
isolated setup; the menu gating is unit-tested through the presentation
policy only by code reading). A pane with a running agent in the dialog
count (the fixtures ran plain shells, so the live dialog always showed 0
running agents; the `(1 running agent)` copy is covered by
`removalPromptNamesThePanesAndAgentsItCloses` and the count by
`removing_a_registration_with_panes_closes_them_and_removes_only_on_confirmation`).
- **화면 증거**: the screenshots are registered in the local run directory
(`agents/runs/hide-sidebar-pinning/live/shots/`, local-only by
repository rule) and described above; no upload channel for GitHub user
attachments was available from this session, so none are inline.

## Product And Scope Result

- PRD: agents/prd/hide-sidebar-pinning/prd.md
- Implementation state: agents/runs/hide-sidebar-pinning/state.json
- Verification report:
agents/runs/hide-sidebar-pinning/verification-report.json (status: PASS)
- Verification summary:
agents/runs/hide-sidebar-pinning/verification-report.md

## Actual Tests

- S1: GREEN - `bash scripts/verify-cargo.sh test` (cwd: ., exit 0)
- S2: GREEN - `bash scripts/verify-swift.sh test` (cwd: ., exit 0)
- S3: GREEN - `bash scripts/verify-cargo.sh lint` (cwd: ., exit 0)

## Actual Observations

- agents/runs/hide-sidebar-pinning/live/shots/13b-charlie-menu.png
(screenshot, observed 2026-09-19T04:39:11.475Z, sha256
408a39a7c72dad1745ab3343af8578f4325cde968a2060eb548471e8dde8df29):
screencapture -R on the candidate window; input via CGEvent bound to the
candidate PID
- agents/runs/hide-sidebar-pinning/live/shots/13e-charlie-pinned.png
(screenshot, observed 2026-09-19T04:39:11.782Z, sha256
8945fa92bb8289be1e2efbe128479fe12120c1907691d54527cdc780b7f45f2c):
screencapture -R on the candidate window; input via CGEvent bound to the
candidate PID
- agents/runs/hide-sidebar-pinning/live/shots/14b-pinned-two.png
(screenshot, observed 2026-09-19T04:39:12.150Z, sha256
e4ea63e32c5095f33da156f70bc60358967038364f61ed9fc67abd58a1ae1ef6):
screencapture -R on the candidate window; input via CGEvent bound to the
candidate PID
- agents/runs/hide-sidebar-pinning/live/shots/15a-alpha-menu.png
(screenshot, observed 2026-09-19T04:39:12.489Z, sha256
ac8dee2309a153a569eed9df47db334f0a5d01f885cc8cdb06680cb13d6531a7):
screencapture -R on the candidate window; input via CGEvent bound to the
candidate PID
- agents/runs/hide-sidebar-pinning/live/shots/15b-remove-dialog.png
(screenshot, observed 2026-09-19T04:39:12.825Z, sha256
674012843bd21c341a78c5512552a72542c52d71c8f2878c95dcc137eb719f41):
screencapture -R on the candidate window; input via CGEvent bound to the
candidate PID
- agents/runs/hide-sidebar-pinning/live/shots/15c-after-remove.png
(screenshot, observed 2026-09-19T04:39:13.163Z, sha256
d37c1712dd6f49877fb4310cc2f48f0ce65d75f7853dd0b6268d73017c79f1a3):
screencapture -R on the candidate window; input via CGEvent bound to the
candidate PID
-
agents/runs/hide-sidebar-pinning/live/shots/16b-remove-nopane-dialog.png
(screenshot, observed 2026-09-19T04:39:13.498Z, sha256
c411e708c062c1f42f1cdf4f9084dac23edd18ad8218d8cde67fa247695684d2):
screencapture -R on the candidate window; input via CGEvent bound to the
candidate PID
-
agents/runs/hide-sidebar-pinning/live/shots/18b-after-remove-focused.png
(screenshot, observed 2026-09-19T04:39:13.841Z, sha256
15adb3b4f7f98187262e941f80624c24faf5dcd54bc574664eee98116374c1cf):
screencapture -R on the candidate window; input via CGEvent bound to the
candidate PID
- agents/runs/hide-sidebar-pinning/live/shots/15d-after-remove-wide.png
(screenshot, observed 2026-09-19T04:39:14.174Z, sha256
99e5967a213ff95af7faf79a49343bde9b4cadda6ee50847aae05c1ccef570ec):
screencapture -R on the candidate window; input via CGEvent bound to the
candidate PID
- agents/runs/hide-sidebar-pinning/live/remove-after-panes.txt (log,
observed 2026-09-19T04:39:14.507Z, sha256
44fcb64c4dcf91c6ec51ef354bddbd5f4fc36f9c40c87bffa85d6ccf7963668f):
screencapture -R on the candidate window; input via CGEvent bound to the
candidate PID
- agents/runs/hide-sidebar-pinning/live/remove-before-ps.txt (log,
observed 2026-09-19T04:39:15.199Z, sha256
dbbfe86c344ccbe492f8819c29622a998235452b426f02485eff74478956ea7f):
screencapture -R on the candidate window; input via CGEvent bound to the
candidate PID
- agents/runs/hide-sidebar-pinning/live/process-survival.txt (log,
observed 2026-09-19T04:39:27.439Z, sha256
9b2deb6199cc3c266aa88538403d7dcf8c8946b813441c6b62f1c196c242056f): ps
-eo pid,command and herdr pane list against the private server
-
agents/runs/hide-sidebar-pinning/live/shots/08b-pin-alpha-unified-rows.png
(screenshot, observed 2026-09-19T04:39:37.964Z, sha256
384e2008ad8c4dbc9068338fb8b142b77544bce98ef74ec8f6886b93d7da9c81):
screencapture -R on the candidate window; input via CGEvent bound to the
candidate PID
-
agents/runs/hide-sidebar-pinning/live/shots/11-relaunch-pinned-reveal.png
(screenshot, observed 2026-09-19T04:39:38.318Z, sha256
434c7488a529bb34433681499fb776b7622a1aa4aa93dfac4852f3bf188b6bbf):
screencapture -R on the candidate window; input via CGEvent bound to the
candidate PID
- agents/runs/hide-sidebar-pinning/live/shots/12b-alpha-unpinned.png
(screenshot, observed 2026-09-19T04:39:38.670Z, sha256
b9f505bc427d1c91f85f8cdf3b229eaa8dd15e88f76d37f9789a22a9d4ad3ff8):
screencapture -R on the candidate window; input via CGEvent bound to the
candidate PID

## Deterministic Verification

- Deterministic verification: PASS
- PRD SHA:
587af69a9e8194a663292388c1a65a9793b793f5867b89ae616a6be5cdb9a175
- Base SHA: 2c3c39b
- Head SHA: 11f1aa8
- Source fingerprint:
054468945e73520b6dd0f6f74d796d26e7c8ac750b2f8bd33c6f7ca23ccdbe39
- Generated: 2026-09-19T05:09:24.716Z
- Agent reviews are visible advisory notes produced by native runtime
subagents.

## Agent Review: Fix Now

Review availability: Fidelity and Code reviews ran as native subagents
on b6d21b4, again on 950f4ae, confirmed on 680ef9d, and confirmed the
origin/main merge at 11f1aa8. No Security review (the PRD is not tagged
high-risk).

Fidelity verdicts at 680ef9d: B1-B8 met, B9 met (code inspection only),
B10-B14 met, B15 met (by design, not re-tested), B16 met (code
inspection, no VoiceOver capture), B17-B20 met.

- **Code, Medium (b6d21b4): re-registering the same folder while its
removal close was in flight got silently retired with it** (registration
ids are path-keyed, so ⇧⌘N on that folder named the entry the retire was
about to delete). Disposition: fixed in 950f4ae. `CreateWorkspace`
refuses a folder whose removal is in flight
(`workspace.remove_in_flight`), `remove_workspace` refuses a project
whose creation is in flight (`workspace.create_in_flight`), and a
creation that lands anyway cancels the removal with
`workspace.remove_cancelled` so the close's late answer authorizes
nothing. Tests
`adding_a_folder_while_its_removal_closes_panes_is_refused_and_a_landed_add_cancels_it`
and `removing_a_project_whose_creation_is_in_flight_is_refused`. Both
reviewers confirmed the fix on the re-review of 950f4ae.
- **Found live, before the reviews (fixed in b6d21b4):** removing the
project that held the focused checkout left
`pane.projection_unavailable` on every sync ("Selected pane w1:p3 is not
available for the selected checkout") and an empty Overview. The retire
path now drops the focus and pane selection with the project, as
`consume_restore_hint` does after a Herdr restart; test
`removing_the_focused_project_moves_focus_off_its_closed_panes`, live
re-check in the rebuilt app (bravo came forward with `w2:p1`).
- No Fix now item remains at 680ef9d (Fidelity and Code both "None").

## Agent Review: Follow-up Improvements

Advisory, outside the current contract:
- Code: `spawn_worktree_close` / `spawn_workspace_close`
(`herdr-core/src/worktree_control.rs`) never release their in-flight
marker if `runtime.lock()` returns `Err` (a poisoned mutex, pre-existing
pattern shared by every worker callback); fix once across them, e.g.
`unwrap_or_else(PoisonError::into_inner)`.
- Code: `project_base_branches` (`herdr-core/src/model.rs`) is never
pruned when a registration is removed (pre-existing gap);
`retire_workspace_registration` is now the natural place.
- Code: `catalog_roots` / `worktree_catalog` stay transiently stale
after a removal until the next sync (deliberate, avoids git under the
lock; self-heals via `resync_navigator_focus`).
- Code: no snapshot field mirrors `workspace_removals_in_flight`, so the
row shows nothing while the close runs (PRD non-goal: no progress UI).
- Fidelity: B9 (no `Pinned` section in remote navigation) holds because
the remote wire never sends `pinned` and the DTO defaults to false;
there is no dedicated test or screenshot for the remote path.
- Fidelity: B16 (VoiceOver) is plausible by construction (standard
`Button`/`Menu`/`Alert`, the pre-existing `HideSectionLabel`) but was
not captured with VoiceOver.
- Fidelity: the three new `set_error` calls pass `retryable: false`;
nothing in the shell keys the banner on it today.
- Fidelity: the in-flight refusals in 950f4ae are not itemized as a
B-line; they serve D-11 ("no half-removed state") and contradict no
decision, flagged for traceability.

## Delivery Staging

- Mode: pr
- Branch: prd/hide-sidebar-pinning (delivery config names
`gen-prd/hide-sidebar-pinning`; the verified head is what is pushed)
- Base: main (0 behind at 11f1aa8)
- Staging include: default allowlist
- Staging exclude: default volatile paths

## Changed Paths Planned For This PR

- DESIGN.md
- design/hide.pen
- docs/BROWSER_PANES.md
- docs/PERFORMANCE_TESTING.md
- docs/README.md
- herdr-core/src/files.rs
- herdr-core/src/live.rs
- herdr-core/src/model.rs
- herdr-core/src/persistence.rs
- herdr-core/src/project_context.rs
- herdr-core/src/runtime.rs
- herdr-core/src/runtime/editor.rs
- herdr-core/src/runtime/events.rs
- herdr-core/src/runtime/projects.rs
- herdr-core/src/runtime/session.rs
- herdr-core/src/runtime/tests.rs
- herdr-core/src/runtime/tests/agents_settings_remote.rs
- herdr-core/src/runtime/tests/editor_preview.rs
- herdr-core/src/runtime/tests/editor_reopen.rs
- herdr-core/src/runtime/tests/projects.rs
- herdr-core/src/runtime/tests/session_navigation.rs
- herdr-core/src/session_sync/replica.rs
- herdr-core/src/sidebar.rs
- herdr-core/src/workspace.rs
- herdr-core/src/worktree_control.rs
- herdr-core/tests/ffi_contract.rs
- macos/Sources/HerdrMacOS/BrowserPaneOpener.swift
- macos/Sources/HerdrMacOS/CoreBridge.swift
- macos/Sources/HerdrMacOS/CoreBridgeEditorSnapshot.swift
- macos/Sources/HerdrMacOS/CoreBridgeSnapshot.swift
- macos/Sources/HerdrMacOS/CoreBridgeWorkspaceSnapshot.swift
- macos/Sources/HerdrMacOS/EditorViewerOverlay.swift
- macos/Sources/HerdrMacOS/HerdrApp.swift
- macos/Sources/HerdrMacOS/HideEnvironment.swift
- macos/Sources/HerdrMacOS/HideMainView.swift
- macos/Sources/HerdrMacOS/HideSidebar.swift
- macos/Sources/HerdrMacOS/HideTheme.swift
- macos/Sources/HerdrMacOS/PDFDocumentView.swift
- macos/Sources/HerdrMacOS/RightPanel.swift
- macos/Sources/HerdrMacOS/ShellMenuCommand.swift
- macos/Sources/HerdrMacOS/ShellModel.swift
- macos/Sources/HerdrMacOS/ShellModelNavigation.swift
- macos/Sources/HerdrMacOS/ShellRootView.swift
- macos/Sources/HerdrMacOS/SidebarList.swift
- macos/Sources/HerdrMacOS/SidebarPresentation.swift
- macos/Sources/HerdrMacOS/WorkspaceOutlinePresentation.swift
- macos/Sources/HerdrMacOS/WorkspaceOutlineView.swift
- macos/Sources/HerdrMacOS/WorktreeTasks.swift
- macos/Tests/HerdrMacOSTests/BrowserPaneOpenerTests.swift
- macos/Tests/HerdrMacOSTests/EditorPreviewTabPresentationTests.swift
- macos/Tests/HerdrMacOSTests/PDFDocumentViewTests.swift
- macos/Tests/HerdrMacOSTests/RightPanelPresentationTests.swift
- macos/Tests/HerdrMacOSTests/SidebarPresentationTests.swift
- macos/Tests/HerdrMacOSTests/WorkspaceOutlineEditingTests.swift
- macos/Tests/HerdrMacOSTests/WorkspaceOutlinePresentationTests.swift
- macos/Tests/HerdrMacOSTests/WorktreeTaskTests.swift
- plugins/browser/browser-pane.mjs
- plugins/browser/browser-pane.test.mjs
- scripts/check-core-bridge-structure.py
- scripts/pen-token-map.json

## Risks, Rollback, And Human Review

- **Runtime mutex**: the pane close runs on the
`herdr-core-workspace-close` thread and re-enters the runtime once with
the result; under the lock the removal path mutates snapshot vectors and
queues the off-lock state save; removal counts ride the existing
per-sync summary pass (one pass over the checkout pane lists, local
registrations only). The in-flight checks compare stored registration
paths and never canonicalize under the lock.
- **Ownership**: Herdr owns pane existence, so the registration is
retired only after Herdr confirms every pane is gone
(`confirmation_state` over `session.snapshot`); the pin is core-owned UI
state persisted to the app state file.
- **Herdr contract**: `pane.close` and `session.snapshot` only, both in
`contracts/herdr-api.schema.json` for the pinned v0.9.1
(`check-herdr-contract.sh --schema-only` passes against the installed
binary).
- **Failure path**: close timeout or refusal → `workspace.remove_failed`
("… The project stays registered; remove it again to close the panes
that remain."); no live connection with panes → same kind, "needs a live
Herdr connection"; add during removal → `workspace.remove_in_flight`;
remove during add → `workspace.create_in_flight`; add landing during
removal → `workspace.remove_cancelled`; pin of an unregistered id →
`workspace.pin_unregistered`. Diagnostics:
`workspace.pinned|unpinned|unregistered`, `remove.close_requested` with
pane ids, `workspace.create.refused_during_removal`.
- **Rollback**: revert the merge commit; the persisted `pinned` flag is
`#[serde(default)]` on both sides, so a build without it reads the state
file unchanged and a build with it reads an older file as unpinned.
- **Not run**: a Herdr close timeout or refusal in the live app
(unit-tested only); a remote device's rows (no remote target in the
isolated setup); the `(N running agents)` dialog copy live (fixtures ran
plain shells; covered by `removalPromptNamesThePanesAndAgentsItCloses`);
VoiceOver.
- **Diff note**: "Changed Paths Planned" below lists the whole span from
the run's baseline 2c3c39b, which includes the paths that arrived with
the `origin/main` merge (#107 and #108: BrowserPaneOpener,
PDFDocumentView, WorkspaceOutline*, editor preview tab files,
docs/BROWSER_PANES.md, plugins/browser, herdr-core/src/files.rs,
ffi_contract.rs). The review diff against `main` is `git diff
origin/main...HEAD` (31 source files + `design/hide.pen`).

## AI tooling

- [ ] 사람이 직접 작성  - [ ] 일부를 AI 도구로 작성  - [x] 대부분을 AI 도구로 작성

**손으로 확인한 것**: every live observation above was made on the running dev
app and read from screenshots and `herdr pane list` / `ps` output, not
inferred from code.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant