From 01b58fc8652b4667464b7d1c83822bcd0676f04c Mon Sep 17 00:00:00 2001 From: yansfil Date: Thu, 1 Oct 2026 01:29:54 +0900 Subject: [PATCH 01/18] Record focused-area tab cycling contract --- agents/prd/focused-area-tab-cycle/prd.md | 82 ++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 agents/prd/focused-area-tab-cycle/prd.md diff --git a/agents/prd/focused-area-tab-cycle/prd.md b/agents/prd/focused-area-tab-cycle/prd.md new file mode 100644 index 0000000000..c7616b7acd --- /dev/null +++ b/agents/prd/focused-area-tab-cycle/prd.md @@ -0,0 +1,82 @@ +--- +topic: "포커스된 영역 안의 탭 순환과 포커스 표시" +status: "ready" +human_approval: "pending" +review_profile: "standard" +review_rationale: "키보드 탐색과 네이티브 브라우저 입력 전달 및 작업 화면의 포커스 표시를 함께 바꾼다." +source_intake: "current conversation" +created_at: "2026-10-01" +updated_at: "2026-10-01" +--- + +# PRD: 포커스된 영역 안의 탭 순환과 포커스 표시 + +## Goal + +hide 사용자가 Agent와 View를 오가면서 현재 키보드를 둔 영역의 이전 탭으로 예측 가능하게 돌아가고, 어느 영역이 키보드를 갖고 있는지 화면에서 바로 알 수 있게 한다. +이슈 #269의 모든 완료 조건을 구현하며, 이미 머지된 #239의 키보드 소유 경계를 확장한다. + +## Non-goals + +- 영역 순환을 프로젝트나 다른 영역까지 확장하지 않는다. 전체 탐색은 별도 Recent Panels로 유지하고, 범위 통합은 별도 요청에서 재검토한다. +- 새로운 창이나 탭을 자동 생성하지 않는다. 기존 탭 탐색에 대상이 없으면 현재 상태를 유지하며, 생성 UX는 기존 계약을 따른다. +- 포커스 표시 때문에 터미널·문서·브라우저 본문을 읽기 어렵게 만들지 않는다. blur는 실제 비교와 성능 검증이 승인 가능한 결과를 낼 때만 채택한다. +- 레이아웃과 선택의 권한을 웹에 옮기거나 새 패키지를 도입하지 않는다. 기존 core 권한과 입력 전달 경계를 확장한다. + +## Decisions + +| D-n | 결정 | 근거 | +| --- | --- | --- | +| D-01 | 데스크톱 Ctrl+Tab과 Ctrl+Shift+Tab은 시작 시점의 정확한 Agent 또는 View area 내부 탭을 MRU 순서로 순환한다. | 이슈 #269의 원하는 동작 및 완료 조건. | +| D-02 | View 문서·diff·네이티브 브라우저 및 각 영역의 탭 바도 같은 키보드 소유 기준을 쓴다. 영역의 식별에는 device, checkout, 영역 종류, area가 모두 포함된다. | 이슈 #269, 현재 두 레이아웃의 area ID가 겹친다는 읽기 전용 조사. | +| D-03 | 수정 키를 누른 동안 순서와 범위를 고정한 미리보기를 표시하고, 놓으면 한 번 확정하며 Escape와 창 blur는 취소한다. | 이슈 #269 및 기존 Recent navigation 계약. | +| D-04 | 전체 Recent Panels는 별도의 명확한 이름을 가진 명령으로 유지하고, 팔레트·메뉴·단축키 설정에서 영역 순환과 구분한다. 기존 Alt+Tab Recent Projects는 유지한다. | 이슈 #269. | +| D-05 | 가정: 전체 Recent Panels의 기본 단축키는 비워 두고 설정에서 배정할 수 있게 한다. 메뉴·팔레트 호출은 수정 키 유지 없이 이전 항목으로 한 번 이동한다. | 사용자가 추가 의사결정을 위임했으며 기존 chord는 영역 순환에 필요하다. | +| D-06 | 브라우저의 Alt+Backquote 계열은 동일한 영역 순환을 수행한다. 사용자 재배정도 실제 수정 키의 해제와 취소 의미를 보존한다. | 이슈 #269 및 기존 공통 단축키 설정의 일관성. | +| D-07 | 가정: 기존 강조색으로 포커스된 영역의 선택을 강하게 표시하고, 나머지 영역의 탭 바와 배경은 낮춘다. 약한 blur와 비교한 뒤 가독성·성능 근거로 최종안을 선택한다. | 이슈 #269의 후보 비교 및 사용자의 되돌릴 수 있는 디자인 의사결정 위임. | +| D-08 | 네이티브 브라우저는 해당 WebContents의 포커스와 키 입력을 기존 호스트 경계로 전달한다. 웹 shell 이벤트만으로 네이티브 입력을 확인했다고 간주하지 않는다. | 현재 네이티브 페이지와 shell 키 리스너가 분리되어 있다는 조사 및 BROWSER_DISPLAYS 계약. | +| D-09 | 같은 범위의 항목이 닫히거나 이동하면 유효한 탭만 남기고, 영역이 사라지면 취소한다. 다른 영역으로 범위를 대체하지 않는다. | 이슈 #269의 영역 경계와 기존 최근 기록의 유효성 규칙. | +| D-10 | 각 이슈의 독립 worktree에서 PR을 만들고 CI 통과 후 main에 merge commit으로 머지한다. 사용자는 완료 후 QA하고, 구현 중 되돌릴 수 있는 결정을 맡긴다. | 사용자 원문: “issue하나당 worktree 파서 /please 로 다 PR올리고 머지하는것까지”, “나대신 추가로 나오는 의사결정 다해주고”. agents/config.json은 PR·CI 감시·worktree를 설정한다. | +| D-11 | engineering/principles.md와 design/principles.md 전체를 읽었으며 engineering 5·7·13·14·15와 design 5·7·9·12·13을 적용한다. 구조에 맞지 않는 리스트·파괴 작업 규칙은 새 해당 표면이 없어 별도 행동으로 번역하지 않는다. | oh-my-principle commit 654485f96b7764c759662d2c3e9e386ebc221cf6, 프로젝트 UI_BEHAVIOR·DESIGN_WORKFLOW·PERFORMANCE_TESTING 계약. | +| D-12 | 입력·레이아웃의 기존 권한을 유지하고, 숨겨진 브라우저나 해제된 탭 때문에 포커스·키 처리가 중복되지 않게 한다. | engineering 5·7·14 및 프로젝트 브라우저 소유·attach 계약. | +| D-13 | 요구사항은 이슈 본문과 현재 대화가 완결된 원천이다. 해당 intake qa-log가 없으므로 Spec Gate는 문서 원천 부재로 건너뛰며, 준비 검사와 구현 후 독립 전체 계약 리뷰는 수행한다. | gen-prd의 conversation-only PRD 계약. 사용자에게 미제공된 완성 PRD의 human_approval은 pending을 유지한다. | + +## Behaviors + +| # | 사용자가 관찰하는 행동 | 결정 | +| --- | --- | --- | +| B1 | Agent pane에 포커스가 있을 때 Ctrl+Tab 한 번은 해당 Agent area의 직전 탭으로 돌아가며 다른 Agent area·View·checkout·Overview로 넘어가지 않는다. | D-01, D-02 | +| B2 | Agent 탭 바의 포커스도 해당 area를 정확히 식별하며 분할된 다른 영역을 임의로 선택하지 않는다. | D-01, D-02 | +| B3 | View 문서와 diff 및 View 탭 바에서 같은 단축키는 해당 View area 내부 탭만 순환한다. | D-01, D-02 | +| B4 | 실제 네이티브 브라우저 페이지에 키보드가 있을 때도 해당 View area 순환이 동작한다. 페이지가 키를 중복 소비하거나 다른 area로 보내지 않는다. | D-02, D-08, D-12 | +| B5 | 수정 키를 누르고 반복하면 시작 시 고정한 MRU 순서의 나머지 탭을 순환하며 Ctrl+Shift+Tab은 역방향으로 움직인다. | D-01, D-03 | +| B6 | 수정 키를 유지하는 동안 후보와 선택을 순환 표시에서 미리 볼 수 있고, 실제 탭·레이아웃의 선택은 해제할 때 한 번만 확정된다. | D-03 | +| B7 | Escape 또는 창 blur로 취소하면 시작 탭과 키보드 소유 영역이 유지된다. 취소 후 새 순환은 현재 유효한 MRU에서 시작한다. | D-03 | +| B8 | 대상 탭이 0개 또는 1개이거나 키보드가 두 영역 밖의 검색·설정·대화상자·Overview 등에 있으면 영역 순환은 다른 영역을 선택하지 않고 현재 상태를 유지한다. | D-01, D-02, D-09 | +| B9 | 진행 중 탭의 닫힘·이동은 해당 범위에서 유효한 후보로만 반영된다. 시작 영역이나 checkout이 사라지면 순환을 취소하고 다른 범위로 넘어가지 않는다. | D-09 | +| B10 | 브라우저 shell의 Alt+Backquote와 역방향 조합도 같은 소유 영역과 MRU·미리보기·확정·취소 규칙을 따른다. | D-06 | +| B11 | 전체 Recent Panels는 별도 명령으로 모든 기존 대상 종류를 탐색할 수 있고, 메뉴·팔레트·단축키 설정과 도움말의 이름이 영역 내 순환과 구별된다. | D-04, D-05 | +| B12 | 전체 Recent Panels와 영역 순환은 메뉴·팔레트 호출 시 유효한 대상 하나로 이동하며 수정 키 해제를 기다리지 않는다. 호출 한 번이 이동 두 번으로 처리되지 않는다. | D-05, D-12 | +| B13 | 단축키 설정에서 두 명령의 현재 배정을 확인하고 재배정할 수 있다. 지원되는 배정은 해당 수정 키의 유지·해제 및 Escape를 일관되게 처리한다. | D-04, D-06 | +| B14 | Alt+Tab의 Recent Projects 대상·순서·확정·취소 동작은 기존 계약을 유지한다. | D-04 | +| B15 | 키보드를 가진 한 영역은 탭 바 선택과 내용 경계에서 강하게 식별되고, 다른 Agent/View 영역은 약한 표시로 구별되며 원래 선택한 탭은 알 수 있다. | D-07, D-11 | +| B16 | View 패널이 열린·고정된·전체 확장된 상태와 좁은 창에서도 같은 포커스 규칙이 보인다. light·dark 테마 모두 한국어 및 터미널·문서·브라우저 내용이 읽힌다. | D-07, D-11 | +| B17 | 페이지나 shell이 포커스를 주고받으면 같은 소유 상태와 표시가 갱신되고, 숨겨진 View·비활성 checkout·delegated canvas가 현재 영역처럼 표시되거나 키를 가로채지 않는다. | D-02, D-08, D-12 | +| B18 | 탐색과 포커스 표시 때문에 새 per-key subprocess나 파일 I/O, 무제한 기록·이벤트 큐가 생기지 않으며 입력을 버리지 않는다. 실패를 사용자가 처리할 수 없으면 진단 로그로 남긴다. | D-11, D-12 | +| B19 | Recent navigation 문서와 메뉴·팔레트·설정·도움말의 범위 및 표시가 실제 동작과 일치한다. | D-04, D-06 | + +## Technical structure + +기존 최근 탐색 흐름에 명시적인 영역 범위를 더하고, 키보드 소유 상태를 실제 화면 표시와 네이티브 입력 전달이 함께 관찰한다. +core가 레이아웃과 확정된 선택을 계속 소유하며, shell은 미리보기와 세션 내 최근 기록만 소유한다. +네이티브 브라우저의 키 전달은 기존 desktop 호스트 경계를 확장하며 새로운 서비스·저장소·권한·Herdr topology API는 도입하지 않는다. + +## Risks + +- area ID가 Agent와 View에서 겹치므로 부분 식별자를 쓰면 잘못된 영역으로 이동한다. 전체 범위를 고정하고 이동·닫힘 경계를 함께 다룬다. +- native browser의 입력과 focus는 renderer 테스트만으로 증명되지 않는다. 정확히 식별된 격리 candidate 앱의 실제 페이지에서 입력·해제·취소를 관찰한다. +- 디자인 선택은 사용자 위임에 따른 가정이며 사후 취향 QA 대상으로 남긴다. 비교안을 task-local scratch에 남기고 자동 생성 design 파일은 정식 생성·이식 경로를 따른다. +- 포커스 dimming은 native page pixels에 자동 적용되지 않는다. 브라우저 화면까지 실제 가독성과 표시를 확인하고, blur는 비용을 측정해 선택한다. +- 운영 앱·서버·panes를 변경하거나 설치 번들을 교체하지 않는다. build·native QA는 worktree와 격리 Herdr에서 진행한다. +- 다른 병렬 PR과 문서가 충돌하면 최신 main 위에서 보존해 조정하고 바뀐 head에 필요한 리뷰·검증을 수행한다. +- 구현 전에 사용자가 추가로 해야 할 계정·비용·인증 작업은 없다. 완료 후 사용자는 포커스 표시의 선호와 실제 업무 흐름을 QA한다. From 2f5ad90b05635018a8a7f67227e06b7aa7115761 Mon Sep 17 00:00:00 2001 From: yansfil Date: Thu, 1 Oct 2026 02:14:51 +0900 Subject: [PATCH 02/18] Cycle recent tabs within the focused area --- design/hide-screens.pen | 526 +++++++++++++++++++++++++-- design/review-targets.json | 83 ++++- desktop/e2e/browser.spec.ts | 119 +++++- desktop/e2e/keys.spec.ts | 4 +- desktop/src/channel.ts | 1 + desktop/src/main/browser.ts | 42 ++- desktop/src/main/host.ts | 4 + desktop/src/main/index.ts | 1 + desktop/src/main/menu.test.ts | 7 +- desktop/src/main/menu.ts | 20 +- desktop/src/preload/index.ts | 5 +- docs/ARCHITECTURE.md | 16 +- docs/BROWSER_DISPLAYS.md | 13 +- docs/DESIGN_WORKFLOW.md | 3 +- docs/UI_BEHAVIOR.md | 46 ++- docs/VERIFICATION.md | 10 + scripts/check-design-contract.mjs | 2 +- scripts/design-review-rules.mjs | 19 +- scripts/design-review.mjs | 4 +- scripts/pen-screens.mjs | 29 +- scripts/tests/design-review.test.mjs | 15 + web/e2e/area-focus-geometry.mjs | 14 + web/e2e/recent.spec.ts | 17 +- web/src/AgentAreas.tsx | 10 + web/src/AreaTree.tsx | 10 +- web/src/Overlays.tsx | 4 +- web/src/Palette.tsx | 1 + web/src/SettingsSheet.tsx | 4 +- web/src/TabBar.tsx | 2 +- web/src/ViewAreas.tsx | 11 +- web/src/areaCycle.test.ts | 86 +++++ web/src/areaCycle.ts | 69 ++++ web/src/gallery/AreaFocusScene.tsx | 41 +++ web/src/gallery/mount.tsx | 5 + web/src/host.ts | 6 +- web/src/keyboard.ts | 69 +++- web/src/search.test.ts | 9 +- web/src/search.ts | 6 +- web/src/shortcuts.test.ts | 17 +- web/src/shortcuts.ts | 25 +- web/src/ui.ts | 8 +- web/src/viewFocus.ts | 26 +- 42 files changed, 1270 insertions(+), 139 deletions(-) create mode 100644 web/e2e/area-focus-geometry.mjs create mode 100644 web/src/areaCycle.test.ts create mode 100644 web/src/areaCycle.ts create mode 100644 web/src/gallery/AreaFocusScene.tsx diff --git a/design/hide-screens.pen b/design/hide-screens.pen index 4e40b8f282..781c858adc 100644 --- a/design/hide-screens.pen +++ b/design/hide-screens.pen @@ -56494,7 +56494,7 @@ { "type": "frame", "id": "ws-agtab1-lo", - "name": "탭 이름과 구성 개선", + "name": "검증 결과 확인", "children": [ { "type": "text", @@ -56523,12 +56523,12 @@ { "type": "text", "id": "ws-agtab1-lo-t", - "name": "탭 이름과 구성 개선", - "content": "탭 이름과 구성 개선", - "fill": "$--foreground", + "name": "검증 결과 확인", + "content": "검증 결과 확인", + "fill": "$--subtle-foreground", "fontFamily": "$--font-ui", "fontSize": "$--text-subhead", - "fontWeight": "600" + "fontWeight": "400" } ], "layout": "horizontal", @@ -56539,12 +56539,7 @@ "$--spacing-xs", "$--spacing-xxs", "$--spacing-xs" - ], - "stroke": "$--foreground", - "strokeWidth": { - "bottom": 2 - }, - "strokeAlignment": "inner" + ] }, { "id": "ws-agtabclose-lo", @@ -56579,7 +56574,8 @@ "height": 32, "layout": "horizontal", "gap": "$--spacing-xxs", - "alignItems": "center" + "alignItems": "center", + "fill": "$--card" }, { "type": "frame", @@ -56725,6 +56721,9 @@ "width": "fill_container", "height": "fill_container", "fill": "$--background", + "stroke": "$--border", + "strokeWidth": "$--size-hairline", + "strokeAlignment": "inner", "padding": "$--spacing-sm", "layout": "vertical", "gap": "$--spacing-xxs" @@ -57176,7 +57175,10 @@ "width": "fill_container", "height": "fill_container", "layout": "vertical", - "gap": 0 + "gap": 0, + "stroke": "$--primary", + "strokeWidth": "$--size-hairline", + "strokeAlignment": "inner" }, { "type": "frame", @@ -58194,7 +58196,8 @@ "height": 32, "layout": "horizontal", "gap": "$--spacing-xxs", - "alignItems": "center" + "alignItems": "center", + "fill": "$--background" }, { "type": "frame", @@ -58340,6 +58343,9 @@ "width": "fill_container", "height": "fill_container", "fill": "$--background", + "stroke": "$--primary", + "strokeWidth": "$--size-hairline", + "strokeAlignment": "inner", "padding": "$--spacing-sm", "layout": "vertical", "gap": "$--spacing-xxs" @@ -59009,7 +59015,8 @@ "height": 32, "layout": "horizontal", "gap": "$--spacing-xxs", - "alignItems": "center" + "alignItems": "center", + "fill": "$--background" }, { "type": "frame", @@ -59155,6 +59162,9 @@ "width": "fill_container", "height": "fill_container", "fill": "$--background", + "stroke": "$--primary", + "strokeWidth": "$--size-hairline", + "strokeAlignment": "inner", "padding": "$--spacing-sm", "layout": "vertical", "gap": "$--spacing-xxs" @@ -59268,7 +59278,8 @@ "height": 32, "layout": "horizontal", "gap": "$--spacing-xxs", - "alignItems": "center" + "alignItems": "center", + "fill": "$--card" }, { "type": "frame", @@ -59414,6 +59425,9 @@ "width": "fill_container", "height": "fill_container", "fill": "$--background", + "stroke": "$--border", + "strokeWidth": "$--size-hairline", + "strokeAlignment": "inner", "padding": "$--spacing-sm", "layout": "vertical", "gap": "$--spacing-xxs" @@ -59745,7 +59759,8 @@ "height": 32, "layout": "horizontal", "gap": "$--spacing-xxs", - "alignItems": "center" + "alignItems": "center", + "fill": "$--background" }, { "type": "frame", @@ -59891,6 +59906,9 @@ "width": "fill_container", "height": "fill_container", "fill": "$--background", + "stroke": "$--primary", + "strokeWidth": "$--size-hairline", + "strokeAlignment": "inner", "padding": "$--spacing-sm", "layout": "vertical", "gap": "$--spacing-xxs" @@ -60424,6 +60442,217 @@ "gap": 0, "fill": "$--card", "clip": true + }, + { + "type": "frame", + "id": "ws-focus-l", + "name": "One keyboard area, other selections readable", + "children": [ + { + "type": "frame", + "id": "ws-focus-l-1", + "name": "Keyboard owner", + "children": [ + { + "type": "frame", + "id": "ws-focus-l-1-bar", + "name": "Tab bar", + "children": [ + { + "id": "ws-focus-l-1-tab1", + "type": "ref", + "ref": "hideui:view-tab", + "name": "Selected Korean tab", + "fill": "$--background", + "stroke": "$--primary", + "strokeWidth": { + "bottom": "$--size-tab-indicator" + }, + "strokeAlignment": "inner", + "descendants": { + "hideui:view-tab-mark": { + "fill": "$--file-document" + }, + "hideui:view-tab-title": { + "fill": "$--foreground", + "content": "한글 노트.md" + }, + "hideui:view-tab-strike": { + "fill": "$--muted-foreground" + }, + "hideui:view-tab-dirty": { + "fill": "$--warning" + }, + "hideui:view-tab-close": { + "enabled": true + } + } + }, + { + "id": "ws-focus-l-1-tab2", + "type": "ref", + "ref": "hideui:view-tab", + "name": "검증 결과.md", + "fill": "$--card", + "descendants": { + "hideui:view-tab-mark": { + "fill": "$--file-document" + }, + "hideui:view-tab-title": { + "fill": "$--subtle-foreground", + "content": "검증 결과.md" + }, + "hideui:view-tab-strike": { + "fill": "$--muted-foreground" + }, + "hideui:view-tab-dirty": { + "fill": "$--warning" + } + } + } + ], + "width": "fill_container", + "height": 32, + "layout": "horizontal", + "fill": "$--background" + }, + { + "type": "frame", + "id": "ws-focus-l-1-body", + "name": "Readable Korean content", + "children": [ + { + "type": "text", + "id": "ws-focus-l-1-text", + "name": "# 한글 노트\n\n현재 입력을 받는 영역만 강조합니다", + "content": "# 한글 노트\n\n현재 입력을 받는 영역만 강조합니다.\n다른 영역의 원래 선택과 내용은 읽을 수 있습니다.\n\nfixture % echo 한글 확인\n한글 확인", + "fill": "$--foreground", + "fontFamily": "$--font-mono", + "fontSize": "$--text-caption", + "fontWeight": "400", + "textGrowth": "fixed-width", + "width": "fill_container" + } + ], + "width": "fill_container", + "height": "fill_container", + "layout": "vertical", + "padding": "$--spacing-sm", + "fill": "$--background", + "stroke": "$--primary", + "strokeWidth": "$--size-hairline", + "strokeAlignment": "inner" + } + ], + "width": "fill_container", + "height": "fill_container", + "layout": "vertical" + }, + { + "type": "frame", + "id": "ws-focus-divider-l", + "name": "Area divider", + "width": "$--size-resize-handle", + "height": "fill_container", + "fill": "$--border" + }, + { + "type": "frame", + "id": "ws-focus-l-2", + "name": "Other area, retained selection", + "children": [ + { + "type": "frame", + "id": "ws-focus-l-2-bar", + "name": "Tab bar", + "children": [ + { + "id": "ws-focus-l-2-tab1", + "type": "ref", + "ref": "hideui:view-tab", + "name": "Selected Korean tab", + "fill": "$--secondary", + "descendants": { + "hideui:view-tab-mark": { + "fill": "$--file-document" + }, + "hideui:view-tab-title": { + "fill": "$--foreground", + "content": "한글 노트.md" + }, + "hideui:view-tab-strike": { + "fill": "$--muted-foreground" + }, + "hideui:view-tab-dirty": { + "fill": "$--warning" + }, + "hideui:view-tab-close": { + "enabled": true + } + } + }, + { + "id": "ws-focus-l-2-tab2", + "type": "ref", + "ref": "hideui:view-tab", + "name": "검증 결과.md", + "fill": "$--card", + "descendants": { + "hideui:view-tab-mark": { + "fill": "$--file-document" + }, + "hideui:view-tab-title": { + "fill": "$--subtle-foreground", + "content": "검증 결과.md" + }, + "hideui:view-tab-strike": { + "fill": "$--muted-foreground" + }, + "hideui:view-tab-dirty": { + "fill": "$--warning" + } + } + } + ], + "width": "fill_container", + "height": 32, + "layout": "horizontal", + "fill": "$--card" + }, + { + "type": "frame", + "id": "ws-focus-l-2-body", + "name": "Readable Korean content", + "children": [ + { + "type": "text", + "id": "ws-focus-l-2-text", + "name": "# 한글 노트\n\n현재 입력을 받는 영역만 강조합니다", + "content": "# 한글 노트\n\n현재 입력을 받는 영역만 강조합니다.\n다른 영역의 원래 선택과 내용은 읽을 수 있습니다.\n\nfixture % echo 한글 확인\n한글 확인", + "fill": "$--foreground", + "fontFamily": "$--font-mono", + "fontSize": "$--text-caption", + "fontWeight": "400", + "textGrowth": "fixed-width", + "width": "fill_container" + } + ], + "width": "fill_container", + "height": "fill_container", + "layout": "vertical", + "padding": "$--spacing-sm", + "fill": "$--background" + } + ], + "width": "fill_container", + "height": "fill_container", + "layout": "vertical" + } + ], + "width": 960, + "height": 440, + "layout": "horizontal", + "fill": "$--background" } ], "theme": { @@ -60940,7 +61169,7 @@ { "type": "frame", "id": "ws-agtab1-do", - "name": "탭 이름과 구성 개선", + "name": "검증 결과 확인", "children": [ { "type": "text", @@ -60969,12 +61198,12 @@ { "type": "text", "id": "ws-agtab1-do-t", - "name": "탭 이름과 구성 개선", - "content": "탭 이름과 구성 개선", - "fill": "$--foreground", + "name": "검증 결과 확인", + "content": "검증 결과 확인", + "fill": "$--subtle-foreground", "fontFamily": "$--font-ui", "fontSize": "$--text-subhead", - "fontWeight": "600" + "fontWeight": "400" } ], "layout": "horizontal", @@ -60985,12 +61214,7 @@ "$--spacing-xs", "$--spacing-xxs", "$--spacing-xs" - ], - "stroke": "$--foreground", - "strokeWidth": { - "bottom": 2 - }, - "strokeAlignment": "inner" + ] }, { "id": "ws-agtabclose-do", @@ -61025,7 +61249,8 @@ "height": 32, "layout": "horizontal", "gap": "$--spacing-xxs", - "alignItems": "center" + "alignItems": "center", + "fill": "$--card" }, { "type": "frame", @@ -61171,6 +61396,9 @@ "width": "fill_container", "height": "fill_container", "fill": "$--background", + "stroke": "$--border", + "strokeWidth": "$--size-hairline", + "strokeAlignment": "inner", "padding": "$--spacing-sm", "layout": "vertical", "gap": "$--spacing-xxs" @@ -61622,7 +61850,10 @@ "width": "fill_container", "height": "fill_container", "layout": "vertical", - "gap": 0 + "gap": 0, + "stroke": "$--primary", + "strokeWidth": "$--size-hairline", + "strokeAlignment": "inner" }, { "type": "frame", @@ -62640,7 +62871,8 @@ "height": 32, "layout": "horizontal", "gap": "$--spacing-xxs", - "alignItems": "center" + "alignItems": "center", + "fill": "$--background" }, { "type": "frame", @@ -62786,6 +63018,9 @@ "width": "fill_container", "height": "fill_container", "fill": "$--background", + "stroke": "$--primary", + "strokeWidth": "$--size-hairline", + "strokeAlignment": "inner", "padding": "$--spacing-sm", "layout": "vertical", "gap": "$--spacing-xxs" @@ -63455,7 +63690,8 @@ "height": 32, "layout": "horizontal", "gap": "$--spacing-xxs", - "alignItems": "center" + "alignItems": "center", + "fill": "$--background" }, { "type": "frame", @@ -63601,6 +63837,9 @@ "width": "fill_container", "height": "fill_container", "fill": "$--background", + "stroke": "$--primary", + "strokeWidth": "$--size-hairline", + "strokeAlignment": "inner", "padding": "$--spacing-sm", "layout": "vertical", "gap": "$--spacing-xxs" @@ -63714,7 +63953,8 @@ "height": 32, "layout": "horizontal", "gap": "$--spacing-xxs", - "alignItems": "center" + "alignItems": "center", + "fill": "$--card" }, { "type": "frame", @@ -63860,6 +64100,9 @@ "width": "fill_container", "height": "fill_container", "fill": "$--background", + "stroke": "$--border", + "strokeWidth": "$--size-hairline", + "strokeAlignment": "inner", "padding": "$--spacing-sm", "layout": "vertical", "gap": "$--spacing-xxs" @@ -64191,7 +64434,8 @@ "height": 32, "layout": "horizontal", "gap": "$--spacing-xxs", - "alignItems": "center" + "alignItems": "center", + "fill": "$--background" }, { "type": "frame", @@ -64337,6 +64581,9 @@ "width": "fill_container", "height": "fill_container", "fill": "$--background", + "stroke": "$--primary", + "strokeWidth": "$--size-hairline", + "strokeAlignment": "inner", "padding": "$--spacing-sm", "layout": "vertical", "gap": "$--spacing-xxs" @@ -64870,6 +65117,217 @@ "gap": 0, "fill": "$--card", "clip": true + }, + { + "type": "frame", + "id": "ws-focus-d", + "name": "One keyboard area, other selections readable", + "children": [ + { + "type": "frame", + "id": "ws-focus-d-1", + "name": "Keyboard owner", + "children": [ + { + "type": "frame", + "id": "ws-focus-d-1-bar", + "name": "Tab bar", + "children": [ + { + "id": "ws-focus-d-1-tab1", + "type": "ref", + "ref": "hideui:view-tab", + "name": "Selected Korean tab", + "fill": "$--background", + "stroke": "$--primary", + "strokeWidth": { + "bottom": "$--size-tab-indicator" + }, + "strokeAlignment": "inner", + "descendants": { + "hideui:view-tab-mark": { + "fill": "$--file-document" + }, + "hideui:view-tab-title": { + "fill": "$--foreground", + "content": "한글 노트.md" + }, + "hideui:view-tab-strike": { + "fill": "$--muted-foreground" + }, + "hideui:view-tab-dirty": { + "fill": "$--warning" + }, + "hideui:view-tab-close": { + "enabled": true + } + } + }, + { + "id": "ws-focus-d-1-tab2", + "type": "ref", + "ref": "hideui:view-tab", + "name": "검증 결과.md", + "fill": "$--card", + "descendants": { + "hideui:view-tab-mark": { + "fill": "$--file-document" + }, + "hideui:view-tab-title": { + "fill": "$--subtle-foreground", + "content": "검증 결과.md" + }, + "hideui:view-tab-strike": { + "fill": "$--muted-foreground" + }, + "hideui:view-tab-dirty": { + "fill": "$--warning" + } + } + } + ], + "width": "fill_container", + "height": 32, + "layout": "horizontal", + "fill": "$--background" + }, + { + "type": "frame", + "id": "ws-focus-d-1-body", + "name": "Readable Korean content", + "children": [ + { + "type": "text", + "id": "ws-focus-d-1-text", + "name": "# 한글 노트\n\n현재 입력을 받는 영역만 강조합니다", + "content": "# 한글 노트\n\n현재 입력을 받는 영역만 강조합니다.\n다른 영역의 원래 선택과 내용은 읽을 수 있습니다.\n\nfixture % echo 한글 확인\n한글 확인", + "fill": "$--foreground", + "fontFamily": "$--font-mono", + "fontSize": "$--text-caption", + "fontWeight": "400", + "textGrowth": "fixed-width", + "width": "fill_container" + } + ], + "width": "fill_container", + "height": "fill_container", + "layout": "vertical", + "padding": "$--spacing-sm", + "fill": "$--background", + "stroke": "$--primary", + "strokeWidth": "$--size-hairline", + "strokeAlignment": "inner" + } + ], + "width": "fill_container", + "height": "fill_container", + "layout": "vertical" + }, + { + "type": "frame", + "id": "ws-focus-divider-d", + "name": "Area divider", + "width": "$--size-resize-handle", + "height": "fill_container", + "fill": "$--border" + }, + { + "type": "frame", + "id": "ws-focus-d-2", + "name": "Other area, retained selection", + "children": [ + { + "type": "frame", + "id": "ws-focus-d-2-bar", + "name": "Tab bar", + "children": [ + { + "id": "ws-focus-d-2-tab1", + "type": "ref", + "ref": "hideui:view-tab", + "name": "Selected Korean tab", + "fill": "$--secondary", + "descendants": { + "hideui:view-tab-mark": { + "fill": "$--file-document" + }, + "hideui:view-tab-title": { + "fill": "$--foreground", + "content": "한글 노트.md" + }, + "hideui:view-tab-strike": { + "fill": "$--muted-foreground" + }, + "hideui:view-tab-dirty": { + "fill": "$--warning" + }, + "hideui:view-tab-close": { + "enabled": true + } + } + }, + { + "id": "ws-focus-d-2-tab2", + "type": "ref", + "ref": "hideui:view-tab", + "name": "검증 결과.md", + "fill": "$--card", + "descendants": { + "hideui:view-tab-mark": { + "fill": "$--file-document" + }, + "hideui:view-tab-title": { + "fill": "$--subtle-foreground", + "content": "검증 결과.md" + }, + "hideui:view-tab-strike": { + "fill": "$--muted-foreground" + }, + "hideui:view-tab-dirty": { + "fill": "$--warning" + } + } + } + ], + "width": "fill_container", + "height": 32, + "layout": "horizontal", + "fill": "$--card" + }, + { + "type": "frame", + "id": "ws-focus-d-2-body", + "name": "Readable Korean content", + "children": [ + { + "type": "text", + "id": "ws-focus-d-2-text", + "name": "# 한글 노트\n\n현재 입력을 받는 영역만 강조합니다", + "content": "# 한글 노트\n\n현재 입력을 받는 영역만 강조합니다.\n다른 영역의 원래 선택과 내용은 읽을 수 있습니다.\n\nfixture % echo 한글 확인\n한글 확인", + "fill": "$--foreground", + "fontFamily": "$--font-mono", + "fontSize": "$--text-caption", + "fontWeight": "400", + "textGrowth": "fixed-width", + "width": "fill_container" + } + ], + "width": "fill_container", + "height": "fill_container", + "layout": "vertical", + "padding": "$--spacing-sm", + "fill": "$--background" + } + ], + "width": "fill_container", + "height": "fill_container", + "layout": "vertical" + } + ], + "width": 960, + "height": 440, + "layout": "horizontal", + "fill": "$--background" } ], "theme": { diff --git a/design/review-targets.json b/design/review-targets.json index c937d8586f..2618241e65 100644 --- a/design/review-targets.json +++ b/design/review-targets.json @@ -6,13 +6,36 @@ "scene": "projects-sidebar", "selector": "nav[data-sidebar]", "frames": [ - {"node": "psb-sidebar-l", "theme": "light", "width": 292, "scale": 1, "content": "reference", "state": "rest"}, - {"node": "psb-sidebar-d", "theme": "dark", "width": 292, "scale": 1, "content": "reference", "state": "rest"} + { + "node": "psb-sidebar-l", + "theme": "light", + "width": 292, + "scale": 1, + "content": "reference", + "state": "rest" + }, + { + "node": "psb-sidebar-d", + "theme": "dark", + "width": 292, + "scale": 1, + "content": "reference", + "state": "rest" + } ], "conditions": { - "themes": ["light", "dark"], - "widths": [292, 240], - "contents": ["reference", "long"] + "themes": [ + "light", + "dark" + ], + "widths": [ + 292, + 240 + ], + "contents": [ + "reference", + "long" + ] }, "states": { "rest": "No pointer on the list and no keyboard focus.", @@ -36,5 +59,55 @@ "Long Korean titles at the narrow width: is what the truncation keeps still recognizable?", "Hover and focus captures: is the feedback visible enough without moving anything?" ] + }, + "area-focus": { + "description": "Keyboard ownership across two View areas using the shared Agent/View area renderer.", + "file": "design/hide-screens.pen", + "sheet": "screen-workspace", + "scene": "area-focus", + "selector": "[data-gallery-scene=area-focus]", + "measurement": "web/e2e/area-focus-geometry.mjs", + "frames": [ + { + "node": "ws-focus-l", + "theme": "light", + "width": 960, + "scale": 1, + "content": "reference", + "state": "rest" + }, + { + "node": "ws-focus-d", + "theme": "dark", + "width": 960, + "scale": 1, + "content": "reference", + "state": "rest" + } + ], + "conditions": { + "themes": [ + "light", + "dark" + ], + "widths": [ + 960, + 720 + ], + "contents": [ + "reference" + ] + }, + "states": { + "rest": "First area owns the keyboard; each area retains its selected tab." + }, + "rules": { + "areaFocus": true + }, + "judgment": [ + "Does exactly one area read as the keyboard owner while the other selected tab remains recognizable?", + "Are Korean text and the native page content readable in the app, including narrow and expanded panels?", + "Compare the readable treatment with the local weak blur experiment and its measured cost." + ] } } diff --git a/desktop/e2e/browser.spec.ts b/desktop/e2e/browser.spec.ts index 51390e7dd4..aab0b164da 100644 --- a/desktop/e2e/browser.spec.ts +++ b/desktop/e2e/browser.spec.ts @@ -26,11 +26,13 @@ let server: http.Server; let origin: string; let cliSequence = 0; let extraWorkspace: string | null = null; +let nativeControlOwned = false; const PAGES: Record = { "/a.html": 'Page A

Page A

', "/b.html": 'Page B

Page B

', "/c.html": 'Page C

Page C

', + "/korean.html": '한글 브라우저

작업 공간 검증

다른 영역의 내용과 선택은 읽을 수 있어야 합니다.

', }; test.beforeAll(async () => { @@ -54,6 +56,12 @@ test.beforeEach(() => { }); test.afterEach(async () => { + let releaseFailure: string | null = null; + if (nativeControlOwned) { + const released = spawnSync("/usr/bin/osascript", ["-e", 'tell application "System Events" to key up control'], { encoding: "utf8", timeout: 10_000 }); + nativeControlOwned = false; + if (released.status !== 0) releaseFailure = released.stderr || "native modifier release failed"; + } const info = test.info(); if (info.status !== info.expectedStatus) console.log(hostLog(run.env).map((line) => JSON.stringify(line)).join("\n")); await app?.close().catch(() => undefined); @@ -61,6 +69,7 @@ test.afterEach(async () => { if (extraWorkspace) herdr.run(["workspace", "close", extraWorkspace]); extraWorkspace = null; run.cleanup(); + expect(releaseFailure).toBeNull(); }); type View = { url: string; title: string; visible: boolean; bounds: { x: number; y: number; width: number; height: number }; pid: number }; @@ -286,9 +295,19 @@ test("browser: a page opens from an agent's pane, follows its area, moves withou await expect.poll(async () => (await views()).filter((view) => view.visible).length).toBe(2); await expect(page.locator("[data-browser-still]")).toHaveCount(0); - // So does Recent Panels while ⌃ is held; Escape keeps the current surface. + // Explicitly bind the separate global command: these pages occupy two + // single-tab areas, so focused-area cycling deliberately does nothing. + await page.locator("[data-open-settings]").click(); + await page.locator('[data-settings-tab="shortcuts"]').click(); + await page.locator('[data-shortcut-record="recent_panel"]').click(); + await page.keyboard.press("Control+KeyG"); + await page.locator('[data-shortcut-apply="recent_panel"]').click(); + await expect(page.locator('[data-shortcut-effective="recent_panel"]')).toHaveText("⌃G"); + await page.keyboard.press("Escape"); + + // Global Recent Panels freezes native pages while its modifier is held. await page.keyboard.down("Control"); - await page.keyboard.press("Tab"); + await page.keyboard.press("KeyG"); const cycle = page.locator("[data-cycle=panels]"); await expect(cycle).toBeVisible(); await expect.poll(async () => (await views()).filter((view) => view.visible).length).toBeLessThan(2); @@ -468,6 +487,102 @@ function menuClick(id: string): Promise { return app!.evaluate(({ Menu }, id) => Menu.getApplicationMenu()!.getMenuItemById(id)!.click(), id); } +/** Real macOS input, refused unless this candidate is the foreground process. */ +function nativeKeys(pid: number, statements: string): void { + const script = `tell application "System Events" +if unix id of first application process whose frontmost is true is not ${pid} then error "candidate lost foreground" +${statements} +end tell`; + const result = spawnSync("/usr/bin/osascript", ["-e", script], { encoding: "utf8", timeout: 10_000 }); + if (statements.includes("key down control")) nativeControlOwned = true; + if (result.status === 0 && statements.includes("key up control")) nativeControlOwned = false; + expect(result.status, result.stderr).toBe(0); +} + +test("area cycle native: page input previews one exact area, releases once and cancels", { tag: NEEDS_FOCUS }, async () => { + ({ app } = await launch(run.env)); + const page = await app.firstWindow(); + const sent = countSent(page); + await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]!.setSize(1280, 800)); + await enterWorkspace(page, "fixture"); + const outside = `${origin}/a.html`; + const previous = `${origin}/b.html`; + const current = `${origin}/korean.html`; + for (const url of [outside, previous]) expect(await openFromCli(url, ["--reveal", "--wait"])).toMatchObject({ ok: true }); + await page.keyboard.press("Meta+KeyK"); + await page.keyboard.type("Expand side panel"); + await page.locator('[data-palette-row="command:panel:expanded"]').click(); + if (await page.locator('[data-tools-toggle="on"]').count()) await page.locator('[data-tools-toggle="on"]').click(); + await tab(page, "Page B").click({ button: "right" }); + await page.locator('[role=menu] [data-menu-item=split_right]').click(); + await expect(page.locator("[data-view-area-id]")).toHaveCount(2); + expect(await openFromCli(current, ["--reveal", "--wait"])).toMatchObject({ ok: true }); + const originalId = await displayIdOf(page, "한글 브라우저"); + const previousId = await displayIdOf(page, "Page B"); + const outsideId = await displayIdOf(page, "Page A"); + const pid = app.process().pid!; + const focus = async (url: string) => { + await app!.evaluate(({ app: electron, BrowserWindow }, url) => { + const window = BrowserWindow.getAllWindows()[0]!; + electron.focus({ steal: true }); window.focus(); + const child = window.contentView.children.find(view => (view as { webContents?: Electron.WebContents }).webContents?.getURL() === url) as unknown as { webContents: Electron.WebContents }; + child.webContents.focus(); + }, url); + await expect.poll(async () => (await zoomOf(url)).focused).toBe(true); + }; + const capture = async (name: string) => { + const dir = process.env.HIDE_E2E_SCREENSHOT_DIR; + if (!dir) return; + const source = await app!.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]!.getMediaSourceId()); + const result = spawnSync("/usr/sbin/screencapture", ["-x", "-o", "-l", source.split(":")[1]!, path.join(dir, `${name}.png`)], { encoding: "utf8" }); + expect(result.status, "exact native window capture failed: " + result.stderr).toBe(0); + fs.writeFileSync(path.join(dir, "area-native-identity.json"), JSON.stringify({ pid, window: source, daemonPid: run.daemonPid(), socket: herdr.socket, state: run.env.HIDE_STATE_DIR, userData: run.env.HIDE_DESKTOP_USER_DATA_DIR, pages: await views() }, null, 2)); + }; + await focus(current); + await expect(page.locator('[data-keyboard-area=true]')).toHaveCount(1); + const selections = () => page.locator('[data-view-tab-bar] [aria-selected=true]').evaluateAll(tabs => tabs.map(tab => tab.getAttribute("data-display"))); + const before = await selections(); + const commits = sent.get("view_layout") ?? 0; + nativeKeys(pid, "key down control\nkey code 48"); + await expect(page.locator('[data-cycle=area] [aria-selected=true]')).toHaveAttribute("data-cycle-row", previousId); + await expect(page.locator(`[data-cycle-row="${outsideId}"]`)).toHaveCount(0); + expect(await selections()).toEqual(before); + expect(sent.get("view_layout") ?? 0).toBe(commits); + await capture("area-native-preview"); + nativeKeys(pid, "key up control"); + await expect(page.locator("[data-cycle]")).toHaveCount(0); + await expect(tab(page, "Page B")).toHaveAttribute("aria-selected", "true"); + await expect.poll(() => sent.get("view_layout") ?? 0).toBe(commits + 1); + await page.waitForTimeout(300); + expect(sent.get("view_layout") ?? 0).toBe(commits + 1); + expect(await inPage(current, "window.tabKeys")).toBe(0); + + // Escape from the actual native page preserves both the selection and owner. + await tab(page, "한글 브라우저").click(); + await focus(current); + const canceled = sent.get("view_layout") ?? 0; + nativeKeys(pid, "key down control\nkey code 48"); + await expect(page.locator("[data-cycle=area]")).toBeVisible(); + nativeKeys(pid, "key code 53\nkey up control"); + await expect(page.locator("[data-cycle]")).toHaveCount(0); + await expect(tab(page, "한글 브라우저")).toHaveAttribute("aria-selected", "true"); + expect(sent.get("view_layout") ?? 0).toBe(canceled); + await expect.poll(async () => (await zoomOf(current)).focused).toBe(true); + await expect(page.locator('[data-keyboard-area=true]')).toHaveCount(1); + await capture("area-native-readable"); + + // A native-window blur cancels a fresh hold; a later release cannot commit it. + nativeKeys(pid, "key down control\nkey code 48"); + await expect(page.locator("[data-cycle=area]")).toBeVisible(); + await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]!.blur()); + await expect(page.locator("[data-cycle]")).toHaveCount(0); + await focus(current); + nativeKeys(pid, "key up control"); + await expect(tab(page, "한글 브라우저")).toHaveAttribute("aria-selected", "true"); + expect(sent.get("view_layout") ?? 0).toBe(canceled); + expect(originalId).not.toBe(previousId); +}); + /** A two-finger pinch at the middle of the page showing `url`, then the page's visual zoom. */ function pinch(url: string): Promise { return app!.evaluate(async ({ BrowserWindow }, url) => { diff --git a/desktop/e2e/keys.spec.ts b/desktop/e2e/keys.spec.ts index ce4c625bf8..24af5bb062 100644 --- a/desktop/e2e/keys.spec.ts +++ b/desktop/e2e/keys.spec.ts @@ -148,7 +148,7 @@ test("cycles: ⌃Tab and ⌥Tab commit once, on releasing the held modifier", as await page.keyboard.down("Control"); await page.keyboard.press("Tab"); await page.keyboard.press("Tab"); - await expect(cycleRow("panels")).toHaveAttribute("data-cycle-row", tabs[2]!); + await expect(cycleRow("area")).toHaveAttribute("data-cycle-row", tabs[2]!); expect(sent.get("focus_tab") ?? 0).toBe(focused); await page.keyboard.up("Control"); await expect(page.locator("[data-cycle]")).toHaveCount(0); @@ -162,7 +162,7 @@ test("cycles: ⌃Tab and ⌥Tab commit once, on releasing the held modifier", as await page.keyboard.press("Tab"); await page.keyboard.press("Tab"); await page.keyboard.press("Shift+Tab"); - await expect(cycleRow("panels")).toHaveAttribute("data-cycle-row", tabs[0]!); + await expect(cycleRow("area")).toHaveAttribute("data-cycle-row", tabs[0]!); await page.keyboard.up("Control"); await expect(canvas).toHaveAttribute("data-canvas", tabs[0]!); await exactlyOnce(sent, "focus_tab", focused + 1, page); diff --git a/desktop/src/channel.ts b/desktop/src/channel.ts index ce492569fd..fc581becda 100644 --- a/desktop/src/channel.ts +++ b/desktop/src/channel.ts @@ -29,3 +29,4 @@ export const BROWSER_SYNC_CHANNEL = "hide:browser-sync"; export const BROWSER_CAPTURE_CHANNEL = "hide:browser-capture"; export const BROWSER_COMMAND_CHANNEL = "hide:browser-command"; export const BROWSER_EVENT_CHANNEL = "hide:browser-event"; +export const BROWSER_CYCLE_END_CHANNEL = "hide:browser-cycle-end"; diff --git a/desktop/src/main/browser.ts b/desktop/src/main/browser.ts index 390ae866f4..e1e42678f1 100644 --- a/desktop/src/main/browser.ts +++ b/desktop/src/main/browser.ts @@ -16,8 +16,8 @@ import { BrowserWindow, ipcMain, Menu, session, shell, WebContentsView, type Ipc import path from "node:path"; import { pathToFileURL } from "node:url"; import type { BrowserHostEvent, BrowserPageState, BrowserPlacement } from "../../../web/src/host"; -import type { CommandId } from "../../../web/src/shortcuts"; -import { BROWSER_CAPTURE_CHANNEL, BROWSER_COMMAND_CHANNEL, BROWSER_EVENT_CHANNEL, BROWSER_SYNC_CHANNEL } from "../channel"; +import { hostChord, isCycleCommand, matchHost, releaseModifier, REGISTRY, type Command, type CommandId } from "../../../web/src/shortcuts"; +import { BROWSER_CAPTURE_CHANNEL, BROWSER_COMMAND_CHANNEL, BROWSER_CYCLE_END_CHANNEL, BROWSER_EVENT_CHANNEL, BROWSER_SYNC_CHANNEL } from "../channel"; import { browserPartition, loadable, MAX_LIVE_VIEWS, nextZoomFactor, overCap, parseCommand, parseSync, parseTarget, remoteRequest, toBounds, viewKey, type PageZoom } from "./browserSync"; import type { HostLog } from "./log"; import { accelerator } from "./menu"; @@ -55,6 +55,16 @@ export class BrowserViews { private readonly pages = new Map(); private readonly configuredSessions = new Set(); private window: BrowserWindow | null = null; + private registry: readonly Command[] = REGISTRY; + private cycleInput: { page: Page; release: string } | null = null; + + setRegistry(registry: readonly Command[]): void { this.registry = registry; } + + private cancelCycle(): void { + const held = this.cycleInput; + this.cycleInput = null; + if (held) this.emit({ kind: "cycle-cancel", workspace: held.page.workspace, id: held.page.id }); + } constructor( private readonly log: HostLog, @@ -63,6 +73,10 @@ export class BrowserViews { private readonly resolve: (workspace: string, id: string, load: number) => Promise, private readonly release: (workspace: string, id: string, load: number) => void, ) { + ipcMain.on(BROWSER_CYCLE_END_CHANNEL, (event) => { + if (!this.trusted(event)) return this.log.event("browser.ipc_refused", { channel: "cycle_end" }); + this.cycleInput = null; + }); ipcMain.on(BROWSER_SYNC_CHANNEL, (event, value: unknown) => { if (!this.trusted(event)) return this.log.event("browser.ipc_refused", { channel: "sync" }); const sync = parseSync(value); @@ -108,7 +122,9 @@ export class BrowserViews { window.webContents.on("did-start-navigation", (details) => { if (details.isMainFrame && !details.isSameDocument) this.hideAll(); }); + window.on("blur", () => this.cancelCycle()); window.on("closed", () => { + this.cancelCycle(); for (const page of [...this.pages.values()]) this.destroy(page, "window_closed"); if (this.window === window) this.window = null; }); @@ -259,6 +275,23 @@ export class BrowserViews { void contents.setVisualZoomLevelLimits(...PINCH_ZOOM_LIMITS).catch((error: unknown) => this.log.event("browser.pinch_zoom_failed", { detail: String(error) })); }); contents.on("before-input-event", (event, input) => { + // Only the shown focused page starts a cycle. Its bounded held input + // remains the owner while a shell overlay temporarily draws its still. + const held = this.cycleInput; + const eventLike = { code: input.code, metaKey: input.meta, altKey: input.alt, shiftKey: input.shift, ctrlKey: input.control }; + const command = input.type === "keyDown" && !input.isComposing ? matchHost(eventLike, this.registry, "electron") : null; + const starts = command && isCycleCommand(command.id) && page.visible && contents.isFocused(); + const continues = held?.page === page && command && isCycleCommand(command.id); + const ends = held?.page === page && ((input.type === "keyUp" && input.key === held.release) || (input.type === "keyDown" && input.key === "Escape")); + if (starts || continues || ends) { + const chord = command && hostChord(command, "electron"); + const release = chord && releaseModifier(chord); + if (!held && release) this.cycleInput = { page, release }; + if (ends) this.cycleInput = null; + event.preventDefault(); + this.emit({ kind: "cycle-input", workspace: page.workspace, id: page.id, type: input.type as "keyDown" | "keyUp", key: input.key, code: input.code, control: input.control, alt: input.alt, meta: input.meta, shift: input.shift }); + return; + } // ⌘+ reaches no menu item (the menu's zoom in is ⌘=), so the page // answers it here unless the operator bound that chord to a command. if (input.type !== "keyDown" || input.code !== "Equal" || !input.meta || !input.shift || input.alt || input.control) return; @@ -278,7 +311,9 @@ export class BrowserViews { this.log.event("browser.page_gone", { reason: details.reason }); this.update(page, { loading: false, failure: `The page stopped (${details.reason})` }); }); - contents.on("focus", () => this.emit({ kind: "focus", workspace: page.workspace, id: page.id })); + contents.on("focus", () => { + if (page.visible) this.emit({ kind: "focus", workspace: page.workspace, id: page.id }); + }); contents.setWindowOpenHandler(({ url }) => { // A new window is another browser display, which the core opens. if (page.route && isFileAddress(page.route.source_url) && remoteRequest(page.route, url).cancel) { @@ -353,6 +388,7 @@ export class BrowserViews { private destroy(page: Page, reason: "closed" | "evicted" | "window_closed"): void { if (reason === "evicted") this.emit({ kind: "gone", workspace: page.workspace, id: page.id, load: page.applied, url: page.state.url }); + if (this.cycleInput?.page === page) this.cancelCycle(); this.pages.delete(page.key); this.release(page.workspace, page.id, page.applied); if (page.report) clearTimeout(page.report); diff --git a/desktop/src/main/host.ts b/desktop/src/main/host.ts index badf7845b5..14b286e0ac 100644 --- a/desktop/src/main/host.ts +++ b/desktop/src/main/host.ts @@ -155,6 +155,10 @@ export class DesktopHost { * window's page on the daemon origin is heard; anything else is logged and * dropped. */ + setBrowserRegistry(registry: readonly import("../../../web/src/shortcuts").Command[]): void { + this.browsers?.setRegistry(registry); + } + listenBindings(apply: (reported: unknown) => void): void { ipcMain.on(BINDINGS_CHANNEL, (event: IpcMainEvent, reported: unknown) => { if (!this.fromShell(event)) { diff --git a/desktop/src/main/index.ts b/desktop/src/main/index.ts index 740cd8ebd8..4c9a43026a 100644 --- a/desktop/src/main/index.ts +++ b/desktop/src/main/index.ts @@ -35,6 +35,7 @@ if (!app.requestSingleInstanceLock()) { // The menu is rebuilt only when the chords it shows change. let shown: string | null = null; const showMenu = (registry: readonly Command[]) => { + host.setBrowserRegistry(registry); const chords = JSON.stringify(registry.map((command) => command.electron)); if (chords === shown) return; shown = chords; diff --git a/desktop/src/main/menu.test.ts b/desktop/src/main/menu.test.ts index 34f25ebb13..12302ebf7a 100644 --- a/desktop/src/main/menu.test.ts +++ b/desktop/src/main/menu.test.ts @@ -12,7 +12,7 @@ describe("the app menu (B9)", () => { expect(() => accelerator({ code: "IntlRo", meta: true })).toThrow(); }); - it("places every clickable command exactly once, and the cycles nowhere", () => { + it("places every clickable command exactly once, including the immediate navigation commands", () => { const placed = Object.values(MENU_LAYOUT).flat().filter((id) => id !== null); expect(new Set(placed).size).toBe(placed.length); const expected = REGISTRY.map((command) => command.id).filter((id) => !KEYBOARD_ONLY.includes(id)); @@ -27,6 +27,11 @@ describe("the app menu (B9)", () => { expect(newTab?.accelerator).toBe("Command+T"); const closeTab = items.find((item) => item.id === "close_tab"); expect(closeTab?.accelerator).toBe("Command+W"); + const cycle = items.find((item) => item.id === "recent_area_tab"); + expect(cycle?.accelerator).toBeUndefined(); + (cycle?.click as () => void)(); + expect(sent).toEqual(["recent_area_tab"]); + sent.length = 0; (newTab?.click as () => void)(); expect(sent).toEqual(["new_tab"]); // No standard item claims a chord the registry owns. diff --git a/desktop/src/main/menu.ts b/desktop/src/main/menu.ts index f312660404..0a7b0eb606 100644 --- a/desktop/src/main/menu.ts +++ b/desktop/src/main/menu.ts @@ -7,7 +7,7 @@ // `menuBindings` resolves with the rules the shell's listener runs. import type { MenuItemConstructorOptions } from "electron"; -import { effectiveRegistry, isNumberedCommand, REGISTRY, type Chord, type Command, type CommandId, type EffectiveRegistry } from "../../../web/src/shortcuts"; +import { effectiveRegistry, isCycleCommand, isNumberedCommand, REGISTRY, type Chord, type Command, type CommandId, type EffectiveRegistry } from "../../../web/src/shortcuts"; const KEY_NAMES: Record = { Enter: "Return", @@ -43,11 +43,9 @@ export function accelerator(chord: Chord): string { /** * Which commands each menu carries, in order; null is a separator. The - * cycles (held-modifier ⌃Tab and ⌥Tab walks), Move to Trash (a chord the - * terminal keeps) and the numbered ⌘1-9 / ⌥1-9 selections (whose target is - * the screen order the page knows, so the page answers them and no - * accelerator here may take the press first) have no click form and stay - * keyboard-only. + * numbered ⌘1-9 / ⌥1-9 selections and Move to Trash stay keyboard-only. + * Cycles have an immediate click form, with input owned by the renderer or + * native page rather than an app-menu accelerator. */ export const MENU_LAYOUT: Readonly> = { app: ["settings"], @@ -58,6 +56,10 @@ export const MENU_LAYOUT: Readonly command.id).filter(isNumberedCommand), ]; function commandItem(command: Command, send: (id: CommandId) => void): MenuItemConstructorOptions { // A command with no chord (the sidebar switch until the operator binds one) is a plain item. - return { id: command.id, label: command.title, accelerator: command.electron ? accelerator(command.electron) : undefined, click: () => send(command.id) }; + return { id: command.id, label: command.title, accelerator: command.electron && !isCycleCommand(command.id) ? accelerator(command.electron) : undefined, click: () => send(command.id) }; } // A reported set is a few pane commands; anything past these caps is not one. diff --git a/desktop/src/preload/index.ts b/desktop/src/preload/index.ts index 2d615e9b5c..b6e11f0b76 100644 --- a/desktop/src/preload/index.ts +++ b/desktop/src/preload/index.ts @@ -9,7 +9,7 @@ import { contextBridge, ipcRenderer, type IpcRendererEvent } from "electron"; import type { BrowserCommand, BrowserHostEvent, BrowserSync } from "../../../web/src/host"; import type { ProbedPath } from "../../../web/src/host"; -import { BINDINGS_CHANNEL, BROWSER_CAPTURE_CHANNEL, BROWSER_COMMAND_CHANNEL, BROWSER_EVENT_CHANNEL, BROWSER_SYNC_CHANNEL, COMMAND_CHANNEL, OPEN_PATH_CHANNEL, PICK_FOLDER_CHANNEL, PROBE_PATHS_CHANNEL, REVEAL_CHANNEL } from "../channel"; +import { BINDINGS_CHANNEL, BROWSER_CAPTURE_CHANNEL, BROWSER_COMMAND_CHANNEL, BROWSER_CYCLE_END_CHANNEL, BROWSER_EVENT_CHANNEL, BROWSER_SYNC_CHANNEL, COMMAND_CHANNEL, OPEN_PATH_CHANNEL, PICK_FOLDER_CHANNEL, PROBE_PATHS_CHANNEL, REVEAL_CHANNEL } from "../channel"; contextBridge.exposeInMainWorld("hideHost", { kind: "electron", @@ -38,6 +38,9 @@ contextBridge.exposeInMainWorld("hideHost", { ipcRenderer.send(OPEN_PATH_CHANNEL, path); }, browser: { + endCycle(): void { + ipcRenderer.send(BROWSER_CYCLE_END_CHANNEL); + }, sync(state: BrowserSync): void { ipcRenderer.send(BROWSER_SYNC_CHANNEL, state); }, diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 162978b8a9..cb35ab6136 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -953,16 +953,23 @@ The core asks Herdr off the lock whether it holds the pane's history: with none Herdr's history is the only witness, because the pinned API does not say whether a pane is on the alternate screen: an inline agent whose output has not yet passed one screen has no history either and gets its own keys, which for Claude Code's default renderer opens its transcript without a search while the whole conversation is still on screen. Claude Code's transcript toggles on the key that opens it, so a screen that already shows its transcript footer gets only the search key; the footer is the one witness the agent offers, and a footer that changed sends the full keys as before. The answer names the request that asked (`find.opened`), so the shell acts on it once. -Settings > Shortcuts rebinds the seven pane commands (split right and down, zoom, close pane, larger, smaller and reset text) in the running host's own set. +Settings > Shortcuts rebinds the pane commands, Toggle sidebar view, focused-area next/previous tabs, and global next/previous Recent Panels in the running host's own set. Each host keeps its set in the core apart from the other's, because the hosts reserve different keys: a browser's in `ui_state.browser_shortcut_bindings`, and the desktop app's in `ui_state.shortcut_bindings`, the macOS chord set, in the removed native app's text form (`command+shift+return`) and command names (`increase_text_size`), with `toggle_conversation` kept but never run here; a save that omits `browser_shortcut_bindings` keeps it. The desktop app honours the operator's existing macOS chord set (user decision 2026-09-26): hided passes the state file the removed native app wrote (`~/Library/Application Support/hide/state.json`) as `shortcut_import_path`, and the core reads only its `shortcut_bindings` field, once, while its own set is empty, then records `shortcut_bindings_imported` so a later reset to defaults stays a reset; a missing file imports nothing and a later launch may still import, and an unreadable one is a diagnostic. The core owns that import rather than any shell (S10), which is why the mechanism survived the removal of the native app that used to write the file. -The window listener, the sheet and the editor all read one effective registry (`effectiveRegistry`), and a chord is refused in its row before it is saved when it breaks the host's rules or is another command's: in a browser it needs ⌘, ⌥ or ⌃ and may not be one Chrome or macOS keeps; in the desktop app it needs ⌘, one printable key or Return, and may not be one macOS or the app menu keeps; a stored set that fails them is dropped whole and the defaults run with a diagnostic. +The window listener, the sheet and the editor all read one effective registry (`effectiveRegistry`), and a chord is refused in its row before it is saved when it breaks the host's rules or is another command's: in a browser it needs ⌘, ⌥ or ⌃ and may not be one Chrome or macOS keeps; in the desktop app a pane command needs ⌘ and one printable key or Return, while a navigation cycle also accepts ⌃ or ⌥ and Tab, and may not be one macOS or the app menu keeps; a stored set that fails them is dropped whole and the defaults run with a diagnostic. While a row records, the listener runs no command, and IME composition never records. The Electron column is the macOS chord set the desktop app uses, with ⌘/ kept from the browser because the macOS set has none: the desktop app has no browser keeping chords, so the moved ones return to ⌘. Each surface reads the running host's column (`web/src/host.ts`: `window.hideHost` means the desktop app): the window listener, the ⌘/ sheet, which drops the "moved for Chrome" note there, and every hint that names a chord. The desktop app menu is built from the same column with the stored macOS set applied (`desktop/src/main/menu.ts`): the shell reports the set over the bridge when it changes and the menu is rebuilt only when its chords do; a click reaches the same `run` path as a chord, and a chord the listener answers calls `preventDefault` in the page. -The held-modifier cycles (⌃Tab and ⌥Tab, ⇧ for backward) walk while the modifier is down and commit one focus when it is released; the desktop e2e drives both through the app. +Focused-area cycles use ⌃Tab in Electron and ⌥Backquote in a browser, with ⇧ for backward; global Recent Panels has distinct command IDs and no default chord, and Recent Projects retains ⌥Tab. +`areaCycle.ts` captures the exact device/checkout/kind/area scope from `viewFocus.ts` and the drawn area frame, filtering the existing bounded MRU rather than adding a second history. +One frozen cycle is held in `ui.ts`; membership changes prune candidates, a disappeared scope cancels, and release dispatches one `focus_tab` with `in_place` or one `view_layout focus`. +`viewFocus.ts` publishes only owner changes to a bounded set of mounted area subscribers; both columns derive their strong tab accent and constant-size content border from that one owner. +Native browser `before-input-event` matches the same effective registry before the page or menu consumes a cycle key and forwards input through the existing trusted browser bridge. +The host retains at most one held page/release modifier, clears it on shell completion, window blur or page destruction, and rejects starts from hidden or unfocused pages. +Cycle menu items carry no accelerator, so native page and renderer input have one owner; menu and palette clicks select immediately through the same command path. +This adds no per-key subprocess, file I/O, second history, notifier fan-out or unbounded queue; the held preview changes page-local state, and only a committed selection reaches the core. The numbered chords (`select_tab_1..9`, `select_agent_1..9`) exist only in the Electron column: their target is the screen order the page knows (`web/src/numbering.ts`: placed tabs in Agent tree/bar order for a local checkout, the Herdr strip order for a device checkout, the rows the Agents list draws from the same `agentTree`), so the page answers them and the app menu carries no item or accelerator for them (`KEYBOARD_ONLY`); a pane chord rebound onto ⌘n is refused as that command's. The hold hint is a pure state machine (`web/src/hints.ts`, ported from the removed native app's `HideHintState`: one modifier set, one deadline, revealed after 150 ms of the exact hold) fed by the same window listener from keydown, keyup, blur and visibilitychange, and cleared by any key during the hold or by a layer opening in the ui store; the listener publishes only the family the state reveals (`ui.hint`: `tabs`, `agents` or null), computed from the registry's chords for the running host, so a browser reveals nothing and an unrevealed hold renders nothing. The keycap is `web/src/components/ui/keycap.tsx`, an absolutely positioned overlay the tab strip and the sidebar agent row draw only while their family is revealed. @@ -979,7 +986,8 @@ The e2e covers each path alone (a Playwright chord, a main-process menu click, o | Reopen closed tab | ⌘⇧T | ⌥⇧T (moved) | ⌘⇧T | | Add project | ⌘⇧N | none (a browser tab has no folder picker, so it offers no Add project) | ⌘⇧N | | Start agent (the start panel) | - | none (Chrome keeps ⌘N); ⌘K `에이전트 시작…` opens it | ⌘N, also File › Start agent | -| Next / previous recent panel (Recent Panels) | ⌃Tab / ⌃⇧Tab | ⌥` / ⌥⇧` (moved) | ⌃Tab / ⌃⇧Tab, committed on releasing ⌃ | +| Next / previous recent tab in focused area | ⌃Tab / ⌃⇧Tab | ⌥` / ⌥⇧` | ⌃Tab / ⌃⇧Tab, committed on releasing ⌃ | +| Next / previous global recent panel | none by default | none by default; bindable in Settings | none by default; menu and palette select immediately | | Next / previous recent project (Recent Projects) | ⌥Tab / ⌥⇧Tab | ⌥Tab / ⌥⇧Tab | ⌥Tab / ⌥⇧Tab | | Search, Open file, Toggle side panel | ⌘K, ⌘P, ⌘⇧B | same chords; ⌘K and ⌘P answered by the palettes | same chords | | Project home | ⌘⇧H | same chord; opens the front checkout's Project Overview | same chord | diff --git a/docs/BROWSER_DISPLAYS.md b/docs/BROWSER_DISPLAYS.md index e91914d45c..277e9ccf09 100644 --- a/docs/BROWSER_DISPLAYS.md +++ b/docs/BROWSER_DISPLAYS.md @@ -96,6 +96,17 @@ The host checks every field of a sync before it places anything and drops a mess Native page reports carry the display's current load stamp, so a late report from a previous reload cannot mark the new request loaded. An evicted page reports its disappearance as disconnected until shown again. +## Keyboard ownership and cycling + +Only a visible native page can report keyboard focus to the shell; the shell resolves its complete Workspace identity and current View area. +The page's `before-input-event` matches the shell's effective Electron shortcut registry for focused-area, global panel and project cycle commands before the page or menu sees them. +One host slot holds the initiating page and actual release modifier, including input received after the overlay hides that page. +The trusted bridge carries only cycle keydown/keyup and cancellation; the shell keeps the frozen scope and preview and owns the single commit. +The shell also reports completion when release arrived in its renderer, so the host cannot retain an old held page into the next cycle. +Window blur and destruction of the held page cancel the host slot, and a hidden or unfocused page cannot begin a cycle. +Cycle menu items are immediate command clicks without accelerators, so one physical key cannot also dispatch a menu selection. +The keyboard area has a strong tab accent and a content boundary outside the native slot; other selected tabs remain readable, with no page blur or recurring capture for focus styling. + ## Zoom While a page holds the keyboard, the text-size commands zoom the page instead of sizing text, the way ⌘= / ⌘- / ⌘0 do in Chrome. @@ -111,7 +122,7 @@ Electron turns pinch off by default, and the limit lives in the page's renderer, ## Overlays A native view is drawn above the page's HTML, so the shell cannot draw over it. -When the palette, a menu, a dialog, a popover, or the Recent Panels or Recent Projects list meets a page's rectangle, the shell asks the host for a capture of the page, draws it in the page's place, and hides the page until the overlay is gone. +When the palette, a menu, a dialog, a popover, or a focused-area, Global Recent Panels or Recent Projects list meets a page's rectangle, the shell asks the host for a capture of the page, draws it in the page's place, and hides the page until the overlay is gone. A shell drag (a tab, a divider, the side panel's edge, an Explorer item) marks the document root with `data-view-drag` or `data-agent-drag` while it runs (`web/src/shellDrag.ts`), and every page of the front Workspace freezes the same way until the mark is gone, so the drag's guide or preview draws over the pages and its drop never reaches one. A new shell drag sets that mark rather than adding its guide to the overlay selector; a drag inside a page never touches the shell and is the page's own. Tooltips are left alone, so a tooltip over a page is drawn under it. diff --git a/docs/DESIGN_WORKFLOW.md b/docs/DESIGN_WORKFLOW.md index 0dd38bf079..dfb16ddce3 100644 --- a/docs/DESIGN_WORKFLOW.md +++ b/docs/DESIGN_WORKFLOW.md @@ -77,7 +77,8 @@ Every name, path and count in a scene is invented example data, so a capture of A design change is judged against the design that was chosen, not against whatever the Pen file says by the time the code lands: a later edit to Pen, or the same wrong change made to Pen and code together, would otherwise hide the drift. `scripts/design-review.mjs` keeps that choice and checks the production screen against it. A target in `design/review-targets.json` names what one run covers: the committed Pen file and its `Screen /` sheet, the Pen nodes it pairs with the screen and each node's width, theme, text scale, content and state, the gallery scene, the states the scene can be put in, the conditions to measure, the default layout rules, and the questions left to a person. -A target exists for `projects-sidebar`; add one when a change touches another screen, not before. +Targets exist for `projects-sidebar` and `area-focus`; add one when a change touches another screen, not before. +`area-focus` measures the production shared area renderer and View tabs with read-only Korean content, enforcing one keyboard area, retained selections, stable geometry and unfiltered content; real terminal and native browser behavior still requires an isolated app capture. ### Keep the chosen design: `baseline` diff --git a/docs/UI_BEHAVIOR.md b/docs/UI_BEHAVIOR.md index 5ce9232837..e3941744bc 100644 --- a/docs/UI_BEHAVIOR.md +++ b/docs/UI_BEHAVIOR.md @@ -24,7 +24,7 @@ The Workspace holds the agent column (the toolbar, then the Agent area), always The panel is closed, open at its width, or expanded over the whole body; the state is stored per Workspace and survives a restart, and a Workspace seen for the first time starts closed. Open, the panel floats over the right part of the agent column and the Agent area keeps its full size underneath, so opening, closing, resizing and expanding the panel never resizes a terminal. The panel is a `--card` surface with a `--border` hairline and a `--radius-lg` top-left corner, and no shadow; a `--spacing-sm` gap in `--background` on its left separates it from the agents. -Everything inside it sits on `--card`: the tabs, the document header, the editor, the diff, a page and a loading view, so a shown View tab is marked by its indicator and title alone, never by a surface of its own. +Everything inside it sits on `--card`: the tabs, the document header, the editor, the diff, a page and a loading view, with the keyboard area's selection accent and the other areas' readable selected-tab background described under View areas. The pane header actions and the right part of an agent's lines under an open panel stay under it; Pin is the remedy. Pin docks the panel instead: the agents end at its left edge and their terminals resize once to fit, and Unpin gives them the body's width back. Pin is not a fourth state: it is stored per Workspace with the width, and a pinned panel still closes, opens, and expands, its agents keeping their docked width under an expanded panel so expanding and restoring resize nothing. @@ -94,7 +94,8 @@ This boundary is an Observer-approved, user-vetoable implementation assumption f The Agent column has its own area tree, separate from the side panel's View tree. Each area has a tab bar, a New tab button and the active tab's live pane canvas; dividers separate areas. -Only the active area's selected tab carries the accent; clicking a tab or pane activates its area and sends the keyboard to that pane. +Only the area holding the keyboard carries the strong selected-tab accent and content boundary, across both Agent and View columns. +Clicking a tab or pane activates its area and sends the keyboard to that pane. All shown tabs stay attached and awake, while only the active area's tab receives read and sleep-visit updates. Pane headers, child chips, relationship controls and pane splits remain inside each canvas; find belongs to the focused pane. ⌘F on a full-screen Claude Code or Codex pane opens that agent's own search over its whole conversation in the pane, with the agent's own keys and count (Claude Code: type, Enter, `n`/`N`; Codex: type, Enter, Ctrl+P), and no find bar appears; any other pane, and an agent drawing inline, gets the find bar. @@ -134,8 +135,11 @@ Retry close reuses that intent's shell, while Dismiss ends the failed intent; de The side panel holds one or more View areas, each with its own tab bar above its own view, split left/right or up/down as often as the limits allow. A split divides one area in two along one axis, and either half can split again along either axis, so every arrangement of side-by-side and stacked areas is a tree of halves. -One area is active: the next file opens there, the palette and the keyboard act on it, and only its active view's tab carries the accent indicator. -Every other area still shows its own active view's tab, with a primary title and no indicator, so the operator sees what each area holds and which one is in charge. +Each layout keeps its own active area for opening and layout actions. +The recorded keyboard owner alone gives one Agent or View area the strong tab accent and content boundary. +Every other area's tab bar uses the card background, and its selected tab keeps a foreground title and secondary background without the strong accent. +The content stays readable and unfiltered; focus adds no content blur, opacity reduction, capture loop or geometry change. +The same rule applies to floating, pinned and expanded View panels, narrow single-area presentation and both themes. An area's tabs each ask for the preferred width and shrink alike down to the title minimum; a file's type mark does not tell files apart, so a View tab keeps its title and never turns to marks the way an Agent tab does. An area whose tabs outrun its width even at that minimum scrolls its own strip so the shown view's tab stays in sight whenever the shown view changes or the area is resized. Clicking a tab or a view, or moving focus to another area from the palette, makes that area active. @@ -416,7 +420,7 @@ A value not yet read leaves the number and the bar out, and zero is drawn as zer The Agents tile's agents are the device's live rows, so it has no last value to age: while the device cannot answer, its ⚠ says why and the number stays empty. Every way into a project's Overview, the project row, its Overview row, the palette and ⌘⇧H, opens Agents in its checkout mode with the lane of the checkout in front selected (outlined and scrolled into view), or main's lane when the checkout in front is elsewhere. -Only Recent Panels (`` ⌥` `` in a browser, `⌃Tab` in the desktop app) brings an Overview back as it was left, its tile, modes, selected lane and opened folds; the view lives on the screen, not in stored settings. +Only Global Recent Panels (a separate command, unbound by default) brings an Overview back as it was left, its tile, modes, selected lane and opened folds; the view lives on the screen, not in stored settings. The PRs view opens only from its tile, a PR chip, `이슈 없는 PR N`, the sidebar's PR card and Recent Panels. The facts line's right end carries the chosen view's mode control: `체크아웃 · 계보` for Agents, the filter and `Board · List · Dependencies` for Issues, and nothing for PRs. @@ -881,17 +885,27 @@ A Home agent reads and edits the projects through their links, the change shows ## Recent navigation -Web owner: `web/src/recent.ts`, `web/src/keyboard.ts`, and `CycleOverlay` in `web/src/Overlays.tsx`. - -Cycling recent surfaces walks every unified surface in recent-use order, across every project, checkout, and device the session holds: terminal, file/editor, and diff tabs, and on the web every View-area display (file, diff, and browser) of this machine and every Herdr tab of each connected device, whose displays the snapshot does not carry (PRD home-device-rail D-16). -On the web, each device's Home Overview and each Project's Overview are rows of the same order once the page has shown them, each reading as its sidebar row does: `Home` over that device's project count with the house mark, or the Project over `Overview` with the layout-dashboard mark; a revisit moves the one row to the front, a Home Overview leaves with its device, and an Overview leaves with its Project. -Committing one of them shows that screen at once, committing a Workspace surface from one shows the Workspace once its checkout is in front, and Recent Projects still restores a Project's last Workspace surface, never its Overview. -The overlay ("Recent Panels", ⌃Tab / ⌃⇧Tab in the desktop app, ⌥` / ⌥⇧` in a browser, where Chrome keeps ⌃Tab) returns to the actually previous surface on a single chord, and repeated chords toggle between the last two surfaces; holding the modifier while repeating the chord walks older visits rather than tab-strip or agent-list order. -A second cycle ("Recent Projects", ⌥Tab / ⌥⇧Tab) scopes to projects globally and restores each project's last used surface. -Committing a row brings its surface forward in its own project and checkout, switching the Workspace when needed, as one event; a display's View area shows if only Agents showed, and the keyboard lands in it. -On the web a surface is in use where the keyboard is: the focused checkout's active display while the keyboard is in its View area (including native browser pages), else its visible Herdr tab, and while a device is in front the tab that device's Herdr shows; a commit's intermediate frames are not visits. -Recent Panels and Recent Projects are one order over every connected device: a row not on the device in front carries that device's chip (`mini`, or `This Mac` with the laptop glyph), and committing it moves the rail, the sidebar and the center to that device and its surface together. -Holding the chord's modifier previews; releasing it commits; Escape keeps the original selection; a menu action commits immediately. +Web owner: `web/src/recent.ts`, `web/src/areaCycle.ts`, `web/src/viewFocus.ts`, `web/src/keyboard.ts`, and `CycleOverlay` in `web/src/Overlays.tsx`. + +Focused-area cycling (⌃Tab / ⌃⇧Tab in the desktop app, ⌥` / ⌥⇧` in a browser) walks the tabs of the exact area holding the keyboard, in recent-use order. +The scope includes device, checkout, Agent or View, and area ID, so identical area IDs in the two columns or another checkout cannot widen the cycle. +A terminal pane or Agent tab bar names its normal Agent area; a document, diff, View tab bar or visible native browser page names its View area. +A delegated canvas outside the area's normal strip, hidden View, tool, search, Settings, dialog or Overview supplies no scope; zero or one tab is a no-op. +Holding the chord's actual modifier freezes the order and scope and previews in Recent Agent tabs or Recent View tabs without moving the committed tab, layout or keyboard owner. +Repeated forward and backward chords walk that frozen order; releasing the modifier commits one in-place selection, and Escape or losing the window cancels without a selection event. +Closed or moved tabs leave the frozen candidates; removal of the origin area or checkout cancels, and no other area replaces it. + +Global Recent Panels is a separate, named command, unbound by default and assignable in Settings alongside the focused-area commands. +It walks every unified surface in recent-use order across projects, checkouts and connected devices: terminal tabs, View files, diffs and browser displays, plus every visited Home and Project Overview. +An Overview revisit moves its one row to the front; its saved tile, modes, selected lane and folds remain page-local, and it leaves the order with its Project or device. +A Global Recent Panels commit shows an Overview at once or brings one Workspace surface forward with one event; a View target also receives the keyboard. +Menu and palette invocations of either family select the next or previous valid target immediately, with no held modifier or second selection. +A bound Global Recent Panels chord keeps the same hold, release and cancellation behavior. +Recent Projects (⌥Tab / ⌥⇧Tab) retains its global project order and restores each Project's last Workspace surface, never its Overview. +Both global lists carry a device chip on a row outside the device in front and move the rail, sidebar and center together when committed. +The session uses one bounded recent-surface history; the area cycle filters it and appends normal area tabs not yet visited. +The shown tab of the recorded keyboard area is the current visit, including native browser pages; intermediate commit frames are not visits. + Reopen Closed Tab is disabled when the session-local recent-close stack is empty or a restore is already running, and restoration works regardless of which surface currently owns focus. Restoration is one action with no confirmation: an in-flight pane shows inline progress, and a restore without a target pane shows a compact inline warning. Missing cwd, an unavailable prior conversation, a missing file, and a retryable failure all use the same inline notice vocabulary, without a banner, card, or modal. diff --git a/docs/VERIFICATION.md b/docs/VERIFICATION.md index c7dddbe3ad..3402906ecf 100644 --- a/docs/VERIFICATION.md +++ b/docs/VERIFICATION.md @@ -101,6 +101,16 @@ osascript -l JavaScript -e 'ObjC.import("CoreGraphics"); ObjC.deepUnwrap(ObjC.ca The grant has been seen to stop matching after the installed app was replaced; report the check as blocked rather than focusing the window to work around it. - Artifacts go under `agents/runs//` ([AGENTS.md](../AGENTS.md#evidence-belongs-outside-the-repository)); the pull request states what was observed, how, and what was not. +### Focused-area navigation + +`web/src/areaCycle.test.ts` checks full device/checkout/kind/area identity, membership, MRU and no-op ownership boundaries. +The `area-focus` design-review target measures the production area renderer with Korean document fixtures in both themes and two widths, including unchanged geometry when keyboard ownership moves. +These checks do not prove native browser input or terminal readability. +The `area cycle native` case in `desktop/e2e/browser.spec.ts` is tagged `@needs-focus`: it uses real macOS modifier input into the isolated candidate's page, counts core selection events, checks page key consumption and captures that exact native window. +Run it only in an agreed foreground QA slot, using `pnpm --dir desktop exec playwright test browser.spec.ts --project needs-focus --no-deps --grep 'area cycle native'` after building this worktree's web and desktop output. +Record the candidate PID/window, private daemon/server/profile and build head beside the captures. +Compare any temporary weak-blur proposal against the readable treatment in the actual terminal, document and native page, with idle and driven measurements, before choosing it. + ## A device check `desktop/e2e/remote-workspace.spec.ts` covers remote routes and `desktop/e2e/device-kit.spec.ts` the install kit against an isolated SSH server; a check against a real device is for what those specs cannot reach. diff --git a/scripts/check-design-contract.mjs b/scripts/check-design-contract.mjs index 1c1efeab90..20378cc671 100644 --- a/scripts/check-design-contract.mjs +++ b/scripts/check-design-contract.mjs @@ -27,7 +27,7 @@ try { || file === 'design/hide-screens.pen' || file === 'design/tokens.json' || file.startsWith('web/src/') - || [...commands, 'pen-tokens.mjs', 'pen-token-map.json', 'pen-bands.mjs', 'pen-foundations.mjs', 'pen-canvas.mjs', 'pen-system.mjs', 'pen-screens.mjs', 'gen-tokens.mjs'].some(name => file === 'scripts/' + name); + || [...commands, 'pen-tokens.mjs', 'pen-token-map.json', 'pen-bands.mjs', 'pen-foundations.mjs', 'pen-canvas.mjs', 'pen-system.mjs', 'pen-screens.mjs', 'pen-screens-disk.mjs', 'gen-tokens.mjs'].some(name => file === 'scripts/' + name); if (!input) continue; if (stage !== '0') throw new Error(`Resolve staged conflict before design check: ${file}`); if (!['100644', '100755'].includes(mode)) throw new Error(`Design inputs must be ordinary files: ${file}`); diff --git a/scripts/design-review-rules.mjs b/scripts/design-review-rules.mjs index 9637fc286c..03ac04b7fb 100644 --- a/scripts/design-review-rules.mjs +++ b/scripts/design-review-rules.mjs @@ -87,6 +87,23 @@ export function noSidewaysOverflow(overflow) { export function evaluate(rules, measured) { const results = []; const add = (rule, result) => results.push({ rule, ...result, pass: result.applicable ? result.problems.length === 0 : null }); + if (rules.areaFocus) { + const states = measured.areaFocus; + const problems = []; + if (states) { + for (const [name, rows] of Object.entries(states)) { + if (rows.filter(row => row.keyboard).length !== 1) problems.push(`${name}: expected exactly one keyboard area`); + if (rows.some(row => row.selected !== 1)) problems.push(`${name}: each area must keep one selected tab`); + if (rows.some(row => row.filter !== 'none')) problems.push(`${name}: content is filtered`); + } + if (states.after.find(row => row.keyboard)?.id !== 'a2') problems.push('keyboard ownership did not follow input into a2'); + for (const row of states.before) { + const after = states.after.find(candidate => candidate.id === row.id); + if (!after || ['x', 'y', 'width', 'height'].some(side => !near(row[side], after[side]))) problems.push(`${row.id}: focus moved or resized content`); + } + } + add('areaFocus', {expected: 'one keyboard area, stable geometry, readable content and retained selections', measured: states ? `${states.before.length} areas before and after focus` : 'no area measurement', problems, applicable: Boolean(states)}); + } if (typeof rules.childIndentPx === 'number') add('childIndentPx', childIndent(measured.columns, rules.childIndentPx)); if (rules.rootsAligned) add('rootsAligned', rootsAligned(measured.columns)); if (rules.stableUnderHover) add('stableUnderHover', stable(measured.rest, measured.hover, 'hover')); @@ -99,7 +116,7 @@ export function evaluate(rules, measured) { return results; } -const KNOWN = new Set(['childIndentPx', 'rootsAligned', 'stableUnderHover', 'stableUnderFocus', 'noOverlap', 'sharedColumns', 'noSidewaysOverflow']); +const KNOWN = new Set(['areaFocus', 'childIndentPx', 'rootsAligned', 'stableUnderHover', 'stableUnderFocus', 'noOverlap', 'sharedColumns', 'noSidewaysOverflow']); function round(value) { return Math.round(value * 10) / 10; diff --git a/scripts/design-review.mjs b/scripts/design-review.mjs index 68aa5d0bb1..4e1c094b1d 100644 --- a/scripts/design-review.mjs +++ b/scripts/design-review.mjs @@ -456,7 +456,7 @@ async function reviewParts(root, {noPen, slug, bundle, manifest, target, themes, // 3. The production screen in Chromium, measured and captured per condition. try { - const geometry = await import(pathToFileURL(path.join(root, 'web/e2e/sidebar-geometry.mjs')).href); + const geometry = await import(pathToFileURL(path.join(root, target.measurement ?? 'web/e2e/sidebar-geometry.mjs')).href); const {origin, browser} = await openBrowser(root, cleanup); const wanted = []; for (const theme of themes) for (const width of widths) for (const content of contents) for (const scale of scales) wanted.push({theme, width, content, scale}); @@ -476,7 +476,7 @@ async function reviewParts(root, {noPen, slug, bundle, manifest, target, themes, await page.locator(target.selector).waitFor(); await page.waitForTimeout(200); if (errors.length) throw new Error(`The scene raised: ${errors.join('; ')}`); - const measured = await measure(page, geometry); + const measured = geometry.measure ? await geometry.measure(page) : await measure(page, geometry); for (const result of evaluate(manifest.rules, measured)) report.rules.push({condition: conditionName(condition), ...result}); for (const state of new Set(['rest', ...states])) { await page.reload(); diff --git a/scripts/pen-screens.mjs b/scripts/pen-screens.mjs index fc311cdb0a..2c6608076b 100644 --- a/scripts/pen-screens.mjs +++ b/scripts/pen-screens.mjs @@ -1588,26 +1588,26 @@ function buildWorkspace(tokens) { // The panel never resizes it while it floats over it. function agentArea(key, active = true, remote = false) { return frame(`ws-agentarea-${key}`, 'Agent area', {width: 'fill_container', height: 'fill_container', layout: 'vertical', gap: 0, fill: '$--background', clip: true, ...(remote ? {stroke: '$--device-remote', strokeWidth: 2, strokeAlignment: 'inner'} : {})}, [ - frame(`ws-agtabs-${key}`, 'Tab bar', {width: 'fill_container', height: ROW, layout: 'horizontal', gap: '$--spacing-xxs', alignItems: 'center'}, [ + frame(`ws-agtabs-${key}`, 'Tab bar', {width: 'fill_container', height: ROW, layout: 'horizontal', gap: '$--spacing-xxs', alignItems: 'center', fill: active ? '$--background' : '$--card'}, [ screenPanelTab(`ws-agtab1-${key}`, 'square-terminal', active ? '탭 이름과 구성 개선' : '검증 결과 확인', active, 'claude'), screenIconButton(`ws-agtabclose-${key}`, 'x', {size: 20}), screenIconButton(`ws-agtabadd-${key}`, 'plus', {size: 20}), ]), screenPaneHeader(`ws-panehdr-${key}`, {label: 'w2:p1', status: 'Working', width: 'fill_container'}), // The xterm viewport takes --background in either theme (commit 7052afa). - frame(`ws-terminal-${key}`, 'Terminal', {width: 'fill_container', height: 'fill_container', fill: '$--background', padding: '$--spacing-sm', layout: 'vertical', gap: '$--spacing-xxs'}, + frame(`ws-terminal-${key}`, 'Terminal', {width: 'fill_container', height: 'fill_container', fill: '$--background', stroke: active ? '$--primary' : '$--border', strokeWidth: HAIR, strokeAlignment: 'inner', padding: '$--spacing-sm', layout: 'vertical', gap: '$--spacing-xxs'}, TERMINAL.map(([line, fill], index) => text(`ws-term${index}-${key}`, line, {fill, mono: true, size: '$--text-caption'}))), ]); } - function agentColumn(key, count, groups = false, remote = null) { + function agentColumn(key, count, groups = false, remote = null, keyboard = true) { const areas = groups ? frame(`ws-agentareas-${key}`, 'Two Agent areas', {width: 'fill_container', height: 'fill_container', layout: 'horizontal', gap: 0}, [ agentArea(`${key}-left`), frame(`ws-agentdivider-${key}`, 'Agent area divider', {width: '$--size-resize-handle', height: 'fill_container', fill: '$--border'}), agentArea(`${key}-right`, false), ]) - : agentArea(key, true, Boolean(remote)); + : agentArea(key, keyboard, Boolean(remote)); return frame(`ws-agents-${key}`, 'Agent column', {width: MAIN_W, height: MAIN_H, layout: 'vertical', gap: 0, fill: '$--background', clip: true}, [toolbar(key, count, remote), areas]); } @@ -1649,7 +1649,7 @@ function buildWorkspace(tokens) { text(`ws-line${index}n-${key}`, String(index), {mono: true, size: '$--text-caption', fill: '$--muted-foreground'}), text(`ws-line${index}t-${key}`, code, {mono: true, size: '$--text-caption'}), ]); - const views = frame(`ws-sp-views-${key}`, 'View areas', {width: 'fill_container', height: 'fill_container', layout: 'vertical', gap: 0}, [ + const views = frame(`ws-sp-views-${key}`, 'View areas', {width: 'fill_container', height: 'fill_container', layout: 'vertical', gap: 0, stroke: '$--primary', strokeWidth: HAIR, strokeAlignment: 'inner'}, [ docHeader, frame(`ws-editor-${key}`, 'Editor body', {width: 'fill_container', height: 'fill_container', layout: 'vertical', gap: '$--spacing-xxs', padding: '$--spacing-sm', clip: true}, ['# 한글 노트', '', '작업 공간의 사이드 패널은 에이전트 위에 뜹니다.', 'Pin 하면 에이전트 옆에 고정됩니다.'].map((code, index) => line(index + 1, code))), @@ -1696,7 +1696,7 @@ function buildWorkspace(tokens) { {title: 'Agent one', status: 'Seen', symbol: '○', statusColor: '$--muted-foreground'}, ]); const main = open - ? frame(`ws-main-${key}`, 'Workspace', {width: MAIN_W, height: MAIN_H, layout: 'none', clip: true}, [{...agentColumn(key, 0), x: 0, y: 0}, sidePanel(key)]) + ? frame(`ws-main-${key}`, 'Workspace', {width: MAIN_W, height: MAIN_H, layout: 'none', clip: true}, [{...agentColumn(key, 0, false, null, false), x: 0, y: 0}, sidePanel(key)]) : frame(`ws-main-${key}`, 'Workspace', {width: MAIN_W, height: MAIN_H, layout: 'vertical', gap: 0}, [agentColumn(key, 2, groups)]); return frame(`ws-wrap-${key}`, groups ? 'Two Agent areas, independent tab bars and live terminals' : open ? 'Side panel open' : 'Side panel closed, two views open', {layout: 'horizontal', gap: '$--spacing-md', alignItems: 'start'}, [sidebar, main]); } @@ -1727,7 +1727,22 @@ function buildWorkspace(tokens) { ]), ]); } - const build = suffix => [workspace(`${suffix}o`, true), workspace(`${suffix}c`, false), workspace(`${suffix}g`, false, true), remoteWorkspace(`${suffix}r`), newTab(`${suffix}n`, true), newTab(`${suffix}e`, false)]; + function focusComparison(suffix) { + const area = (active, at) => { + const key = `focus-${suffix}-${at}`; + return frame(`ws-${key}`, active ? 'Keyboard owner' : 'Other area, retained selection', {width: 'fill_container', height: 'fill_container', layout: 'vertical'}, [ + frame(`ws-${key}-bar`, 'Tab bar', {width: 'fill_container', height: ROW, layout: 'horizontal', fill: active ? '$--background' : '$--card'}, [ + themedXref(`ws-${key}-tab1`, 'view-tab', 'Selected Korean tab', {fill: active ? '$--background' : '$--secondary', ...(active ? {stroke: '$--primary', strokeWidth: {bottom: '$--size-tab-indicator'}, strokeAlignment: 'inner'} : {})}, {'view-tab-title': {content: '한글 노트.md', fill: '$--foreground'}, 'view-tab-close': {enabled: true}}), + screenViewTab(`ws-${key}-tab2`, {title: '검증 결과.md', active: false}), + ]), + frame(`ws-${key}-body`, 'Readable Korean content', {width: 'fill_container', height: 'fill_container', layout: 'vertical', padding: '$--spacing-sm', fill: '$--background', ...(active ? {stroke: '$--primary', strokeWidth: HAIR, strokeAlignment: 'inner'} : {})}, [ + text(`ws-${key}-text`, '# 한글 노트\n\n현재 입력을 받는 영역만 강조합니다.\n다른 영역의 원래 선택과 내용은 읽을 수 있습니다.\n\nfixture % echo 한글 확인\n한글 확인', {mono: true, size: '$--text-caption', width: 'fill_container'}), + ]), + ]); + }; + return frame(`ws-focus-${suffix}`, 'One keyboard area, other selections readable', {width: 960, height: 440, layout: 'horizontal', fill: '$--background'}, [area(true, 1), frame(`ws-focus-divider-${suffix}`, 'Area divider', {width: '$--size-resize-handle', height: 'fill_container', fill: '$--border'}), area(false, 2)]); + } + const build = suffix => [workspace(`${suffix}o`, true), workspace(`${suffix}c`, false), workspace(`${suffix}g`, false, true), remoteWorkspace(`${suffix}r`), newTab(`${suffix}n`, true), newTab(`${suffix}e`, false), focusComparison(suffix)]; return screenSheet('screen-workspace', 'Screen / Workspace', 'web/src/WorkspaceScreen.tsx, AreaTree.tsx, AgentAreas.tsx, TabBar.tsx, ViewAreas.tsx, Tools.tsx: the Workspace with its side panel (Component / Side panel, issue 170) open at full height over the agent column, then closed with two views still open, and with two Agent areas using the shared divider and independent tab bars. The toolbar spans only the agent column and holds no tool toggles; row 1 of the panel holds the area tabs and their New tab, then the tool-column toggle, Expand, Pin and the panel toggle, which the toolbar carries with the open-view count while the panel is closed; row 2 holds the document header and the Explorer and History tool tabs. A Korean file name verifies B11 wrapping. Below them a remote device in front (PRD home-device-rail D-15): the toolbar starts with a band in the device color (--device-remote) carrying the server glyph and the device name ahead of the path, and the agent pane is framed in the same color; This Mac in front has neither.', build, build); } diff --git a/scripts/tests/design-review.test.mjs b/scripts/tests/design-review.test.mjs index 9d28322f48..9c33b706c0 100644 --- a/scripts/tests/design-review.test.mjs +++ b/scripts/tests/design-review.test.mjs @@ -9,6 +9,21 @@ import {childIndent, evaluate, rootsAligned, sharedColumns, stable} from '../des const repository = fileURLToPath(new URL('../../', import.meta.url)); +test('area focus follows the keyboard without changing selected tabs or geometry', () => { + const row = (id, keyboard) => ({id, keyboard, x: id === 'a1' ? 0 : 480, y: 0, width: 480, height: 440, selected: 1, filter: 'none'}); + const measured = {areaFocus: {before: [row('a1', true), row('a2', false)], after: [row('a1', false), row('a2', true)]}}; + assert.equal(evaluate({areaFocus: true}, measured)[0].pass, true); + measured.areaFocus.after[0].keyboard = true; + measured.areaFocus.after[1].width -= 2; + measured.areaFocus.after[1].filter = 'blur(1px)'; + const failed = evaluate({areaFocus: true}, measured)[0]; + assert.equal(failed.pass, false); + assert.ok(failed.problems.some(problem => problem.includes('keyboard'))); + assert.ok(failed.problems.some(problem => problem.includes('moved or resized'))); + assert.ok(failed.problems.some(problem => problem.includes('filter'))); + assert.equal(evaluate({areaFocus: true}, {})[0].pass, null); +}); + // -- the rules, with expected answers written from the rule, not the code ----- const columns = (...rows) => [{list: 'main', rows: rows.map(([pane, depth, mark, title]) => ({pane, depth, mark, title}))}]; diff --git a/web/e2e/area-focus-geometry.mjs b/web/e2e/area-focus-geometry.mjs new file mode 100644 index 0000000000..e8a341fc0f --- /dev/null +++ b/web/e2e/area-focus-geometry.mjs @@ -0,0 +1,14 @@ +// Observed geometry and focus from the production area renderer. Expected +// values come from the chosen design bundle, never from these measurements. +export async function measure(page) { + const read = () => page.locator('[data-view-area-id]').evaluateAll(areas => areas.map(area => { + const box = area.getBoundingClientRect(); + const body = area.querySelector('[data-view-body]'); + return { id: area.dataset.viewAreaId, keyboard: area.dataset.keyboardArea === 'true', x: box.x, y: box.y, width: box.width, height: box.height, selected: area.querySelectorAll('[role=tab][aria-selected=true]').length, filter: globalThis.getComputedStyle(body).filter }; + })); + const before = await read(); + await page.locator('[data-view-area-id=a2] textarea').focus(); + await page.waitForTimeout(30); + const after = await read(); + return { areaFocus: { before, after } }; +} diff --git a/web/e2e/recent.spec.ts b/web/e2e/recent.spec.ts index eee2588194..4a107553ff 100644 --- a/web/e2e/recent.spec.ts +++ b/web/e2e/recent.spec.ts @@ -1,5 +1,5 @@ // Recent navigation on an isolated pinned Herdr and hided -// (docs/UI_BEHAVIOR.md, Recent navigation): Recent Panels (⌥` in a browser) +// (docs/UI_BEHAVIOR.md, Recent navigation): explicitly bound global Recent Panels // walks one order over Herdr tabs and View displays across checkouts and // commits one event on releasing ⌥; Recent Projects (⌥Tab) brings the // previous project back on the surface it was last used on. @@ -47,6 +47,15 @@ test("Recent Panels crosses checkouts onto a display and a tab; Recent Projects const canvas = page.locator("[data-canvas]").first(); const cycleRow = page.locator("[data-cycle] [aria-selected=true]"); + // Global Recent Panels is separate and unbound by default. + await page.locator("[data-open-settings]").click(); + await page.locator('[data-settings-tab="shortcuts"]').click(); + await page.locator('[data-shortcut-record="recent_panel"]').click(); + await page.keyboard.press("Alt+KeyG"); + await page.locator('[data-shortcut-apply="recent_panel"]').click(); + await expect(page.locator('[data-shortcut-effective="recent_panel"]')).toHaveText("⌥G"); + await page.keyboard.press("Escape"); + // plan.txt pinned in the fixture Workspace's View area, the keyboard in it. await showExplorer(page); await page.locator(`[data-explorer-row="${path.join(root, "plan.txt")}"]`).dblclick(); @@ -64,7 +73,7 @@ test("Recent Panels crosses checkouts onto a display and a tab; Recent Projects // ⌥` once, held: the previous surface is the other checkout's display. const focusCheckouts = sent.get("focus_checkout") ?? 0; await page.keyboard.down("Alt"); - await page.keyboard.press("Backquote"); + await page.keyboard.press("KeyG"); await expect(cycleRow).toHaveAttribute("data-cycle-row", display!); await expect(cycleRow).toHaveAttribute("data-cycle-kind", "file"); await expect(page.locator("[data-cycle=panels]")).toContainText("Recent Panels"); @@ -83,7 +92,7 @@ test("Recent Panels crosses checkouts onto a display and a tab; Recent Projects // ⌥` again goes straight back to beta's tab: one focus_tab across checkouts. const focusTabs = sent.get("focus_tab") ?? 0; await page.keyboard.down("Alt"); - await page.keyboard.press("Backquote"); + await page.keyboard.press("KeyG"); await expect(cycleRow).toHaveAttribute("data-cycle-row", betaTab); await page.keyboard.up("Alt"); await expect(canvas).toHaveAttribute("data-canvas", betaTab); @@ -106,7 +115,7 @@ test("Recent Panels crosses checkouts onto a display and a tab; Recent Projects // agent it is, the neutral mark for a tab of several, a file's own mark. const quiet = [sent.get("focus_checkout") ?? 0, sent.get("focus_tab") ?? 0]; await page.keyboard.down("Alt"); - await page.keyboard.press("Backquote"); + await page.keyboard.press("KeyG"); await expect(page.locator("[data-cycle=panels]")).toBeVisible(); const marks = (row: string) => page.locator(`[data-cycle=panels] [data-cycle-row="${row}"] [data-cycle-marks]`); await expect(marks(betaTab)).toHaveAttribute("data-cycle-marks", "codex"); diff --git a/web/src/AgentAreas.tsx b/web/src/AgentAreas.tsx index 59b5418427..051f199f9e 100644 --- a/web/src/AgentAreas.tsx +++ b/web/src/AgentAreas.tsx @@ -16,12 +16,15 @@ import { numberOf, numberedTabs } from "./numbering"; import { useUiStore } from "./ui"; import { AgentTab } from "./TabBar"; import { agentEntries, workspaceViewOf } from "./workspace"; +import { areasOf } from "./areaLayout"; +import { useKeyboardOwner } from "./viewFocus"; const SharedAgentTree = createAreaTree("agent"); export function AgentAreas({ checkout, actions, deviceId = "local", remoteBody }: { checkout: Checkout; actions: Actions; deviceId?: string; remoteBody?: React.ReactNode }) { const [renaming, setRenaming] = useState(null); const saved = useShellStore((s) => workspaceViewOf(s.rest)?.agent_layout); const numbered = useUiStore((s) => s.hint === "tabs"); + const owner = useKeyboardOwner(); const entries = agentEntries(checkout); const remote = deviceId !== "local"; const remoteLayout = useMemo(() => ({ @@ -35,6 +38,13 @@ export function AgentAreas({ checkout, actions, deviceId = "local", remoteBody } const label = (id: string) => entries.find((entry) => entry.source_id === id)?.label ?? id; const adapter: AreaAdapter = { words: AGENT_WORDS, + keyboardArea: owner.kind !== "none" && owner.workspace === checkout.id + ? owner.kind === "agent" ? owner.areaId ?? null + : owner.kind === "pane" ? areasOf(layout.root).find((area) => { + const shown = layout.canvases[area.id] ?? area.active; + return area.displays.some((tab) => tab.id === shown) && checkout.tabs.find((tab) => tab.id === shown)?.panes.some((pane) => pane.id === owner.paneId); + })?.id ?? null : null + : null, barAttributes: { "data-tab-bar": checkout.id, ...(remote ? { "data-remote-tab-bar": "true" } : {}) }, splitUnavailable: remote ? REMOTE_GROUP_REASON : undefined, label: (item) => label(item.id), diff --git a/web/src/AreaTree.tsx b/web/src/AreaTree.tsx index 66809682d9..a1f8ef8efd 100644 --- a/web/src/AreaTree.tsx +++ b/web/src/AreaTree.tsx @@ -45,6 +45,8 @@ function tabSlot(selected: boolean, icon: boolean): string { export type DrawnArea = { layout: AreaLayout; geometry: Geometry; sizes: LayoutSizes }; export type AreaAdapter = { words: AreaWords; + /** The page's keyboard owner, independent of each layout's committed active area. */ + keyboardArea?: string | null; barAttributes?: Record; shown?: (area: Area) => I | null; splitUnavailable?: string; @@ -423,6 +425,7 @@ function AreaView({ area, index, count, switcher }: { area: Area; index: numb const tree = useTree(); const display = tree.adapter.shown ? tree.adapter.shown(area) : area.displays.find((row) => row.id === area.active) ?? null; const active = tree.layout.active_area === area.id; + const keyboard = tree.adapter.keyboardArea === area.id; // The operator's pointer, or Tab, into a display makes it the one they // work in; a focus the page moved itself asks for nothing (B20). const claim = () => { @@ -435,10 +438,11 @@ function AreaView({ area, index, count, switcher }: { area: Area; index: numb aria-label={`${tree.adapter.words.plural.slice(0, -1)} ${index + 1} of ${count}`} {...data("area-id", area.id)} data-active-area={active ? "true" : "false"} + data-keyboard-area={keyboard ? "true" : "false"} > - +
{ @@ -501,7 +505,7 @@ function AreaTabBar({ area, active, index, count, switcher }: { area: Area; a return () => observer.disconnect(); }, [area.active, area.displays.length, icon]); return ( -
+
{area.displays.map((display) => ( diff --git a/web/src/Overlays.tsx b/web/src/Overlays.tsx index 8a9fb5ad8f..62fd389293 100644 --- a/web/src/Overlays.tsx +++ b/web/src/Overlays.tsx @@ -34,8 +34,8 @@ export function CycleOverlay() { const registry = useShellStore((s) => hostRegistry(s.rest?.ui_state, hostKind()).registry); if (!cycle) return null; const { start, rows } = visibleWindow(cycle.items, cycle.index); - const title = cycle.kind === "panels" ? "Recent Panels" : "Recent Projects"; - const chord = displayCommand(cycle.kind === "panels" ? "recent_panel" : "recent_project", hostKind(), registry); + const title = cycle.kind === "area" ? `Recent ${cycle.scope?.kind === "view" ? "View" : "Agent"} tabs` : cycle.kind === "panels" ? "Global Recent Panels" : "Recent Projects"; + const chord = displayCommand(cycle.kind === "area" ? "recent_area_tab" : cycle.kind === "panels" ? "recent_panel" : "recent_project", hostKind(), registry); return createPortal(
diff --git a/web/src/Palette.tsx b/web/src/Palette.tsx index fbb040a500..65b5d47277 100644 --- a/web/src/Palette.tsx +++ b/web/src/Palette.tsx @@ -221,6 +221,7 @@ function SearchPalette({ actions }: { actions: Actions }) { else if ("tool" in entry.command) actions.setTool(entry.command.tool, entry.command.visible); else if ("agent" in entry.command) actions.runAgentCommand(entry.command.agent); else if ("view" in entry.command) actions.runViewCommand(entry.command.view); + else if ("navigation" in entry.command) useUiStore.getState().setCommandRequest({ id: entry.command.navigation }); else if ("startAgent" in entry.command) actions.openStartPanel(); else actions.openFilePaletteBeside(); } else if (entry.kind === "device" && entry.deviceId) { diff --git a/web/src/SettingsSheet.tsx b/web/src/SettingsSheet.tsx index 0915b8f54c..07cf67c371 100644 --- a/web/src/SettingsSheet.tsx +++ b/web/src/SettingsSheet.tsx @@ -1147,10 +1147,10 @@ function ShortcutsTab({ actions }: { actions: Actions }) { return ( <> diff --git a/web/src/TabBar.tsx b/web/src/TabBar.tsx index 8e7e08bfca..75b90b0f01 100644 --- a/web/src/TabBar.tsx +++ b/web/src/TabBar.tsx @@ -134,7 +134,7 @@ const TabButton = memo(function TabButton({ data-tab-kind={entry.kind} data-closing={closing ? "true" : "false"} className={`group relative flex min-w-0 flex-1 cursor-default select-none items-center gap-xs text-caption outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring ${fit.tab} ${ - active ? "bg-background text-foreground" : "text-subtle-foreground hover:bg-accent" + active ? `text-foreground ${areaActive ? "bg-background" : "bg-secondary"}` : "text-subtle-foreground hover:bg-accent" } ${dragging ? "opacity-[var(--opacity-dimmed)]" : ""}`} onPointerDown={onPointerDown} onClick={onSelect} diff --git a/web/src/ViewAreas.tsx b/web/src/ViewAreas.tsx index 1551ef1acd..70b05b0023 100644 --- a/web/src/ViewAreas.tsx +++ b/web/src/ViewAreas.tsx @@ -9,11 +9,11 @@ import { Hint } from "./components/ui/tooltip"; import { hostKind } from "./host"; import { DisplayEditor, DocumentKeeper } from "./Editor"; import { fileIcon } from "./fileIcons"; -import { editorTabFor, type ViewDisplaySnapshot, type ViewLayoutSnapshot } from "./snapshot"; +import { editorTabFor, frontCheckout, type ViewDisplaySnapshot, type ViewLayoutSnapshot } from "./snapshot"; import { useShellStore } from "./store"; import { useUiStore } from "./ui"; import { displayCommand } from "./shortcuts"; -import { noteDrawnViews } from "./viewFocus"; +import { noteDrawnViews, useKeyboardOwner } from "./viewFocus"; import { displayIdentity, displayMenu, focusRequestArrived, placeKey, shownDisplays, workspaceKey, showsSameDocument, VIEW_WORDS, type ViewMenuId, type ViewWorkspace } from "./viewLayout"; import { locateDisplay } from "./areaLayout"; import { workspaceViewOf } from "./workspace"; @@ -48,6 +48,8 @@ export function ViewAreas({ actions, trailing = null }: { actions: Actions; trai const SharedViewTree = createAreaTree("view"); function ViewTree({ layout, deviceId, path, trailing, actions }: { layout: ViewLayoutSnapshot; deviceId: string; path: string; trailing: React.ReactNode; actions: Actions }) { + const owner = useKeyboardOwner(); + const checkoutId = useShellStore((s) => frontCheckout(s.rest)?.id ?? null); const workspace = useMemo(() => ({ device_id: deviceId, path }), [deviceId, path]); const key = workspaceKey(workspace); const [body, setBody] = useState(null); @@ -82,6 +84,7 @@ function ViewTree({ layout, deviceId, path, trailing, actions }: { layout: ViewL const adapter: AreaAdapter = { words: VIEW_WORDS, + keyboardArea: owner.kind === "view" && owner.workspace === checkoutId ? owner.areaId : null, label: (display) => display.label, sameContent: showsSameDocument, tab: (display, interaction) => , @@ -131,7 +134,7 @@ function DisplayBody({ display, workspace, actions }: { display: ViewDisplaySnap } /** One display's tab: its kind's mark, italic while a preview, its save marks, and its whole identity (B2, B21). */ -function DisplayTab({ display, interaction, actions }: { display: ViewDisplaySnapshot; interaction: AreaTabInteraction; actions: Actions }) { +export function DisplayTab({ display, interaction, actions }: { display: ViewDisplaySnapshot; interaction: AreaTabInteraction; actions: Actions }) { const { selected, areaActive } = interaction; const dirty = useShellStore((s) => editorTabFor(s.editor, display.tab_id)?.dirty ?? false); const saving = useShellStore((s) => display.tab_id !== null && s.savingTabs.has(display.tab_id)); @@ -154,7 +157,7 @@ function DisplayTab({ display, interaction, actions }: { display: ViewDisplaySna data-unavailable={unavailable ? "true" : "false"} data-view-state={display.state} className={`group relative flex min-w-0 flex-1 cursor-default select-none items-center gap-xs px-sm text-caption outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring ${ - selected ? "text-foreground" : "text-subtle-foreground hover:bg-accent" + selected ? `text-foreground ${areaActive ? "bg-background" : "bg-secondary"}` : "text-subtle-foreground hover:bg-accent" } ${interaction.dragging ? "opacity-[var(--opacity-dimmed)]" : ""}`} onPointerDown={interaction.press} onClick={() => { diff --git a/web/src/areaCycle.test.ts b/web/src/areaCycle.test.ts new file mode 100644 index 0000000000..0c3f37f62a --- /dev/null +++ b/web/src/areaCycle.test.ts @@ -0,0 +1,86 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { areaCycle, focusedCycleScope } from "./areaCycle"; +import { noteAreaFrame } from "./areaFrames"; +import { areaGeometry } from "./areaLayout"; +import { createActions } from "./actions"; +import { commitCycle, reconcileHeldCycle } from "./keyboard"; +import { observeEntries, resetRecent, tabSurface } from "./recent"; +import type { SnapshotRest } from "./snapshot"; +import { useShellStore } from "./store"; +import { useUiStore } from "./ui"; + +// a1 exists independently in Agent and View; another Agent area and +// checkout both contain tabs that must never leak into the cycle. +function world(): SnapshotRest { + const limits = { areas: 6, depth: 5, displays: 64 }; + const tabs = ["t1", "t2", "t3", "outside"].map((id) => ({ id, label: id, panes: [{ id: `${id}-pane` }], workspace_id: "w", checkout_id: "c", empty: false, delegated: false })); + const checkout = { id: "c", workspace_id: "w", path: "/fixture", label: "fixture", tabs, active_tab_id: "t1", strip: [] }; + return { + navigator: { focused_device_id: "local", focused_checkout_id: "c", focused_workspace_id: "w", devices: [{ id: "local", label: "This Mac", kind: "local", state: "local" }], workspaces: [{ id: "w", label: "fixture", device_id: "local", checkouts: [checkout, { ...checkout, id: "other", path: "/other", tabs: [{ ...tabs[0], id: "other-tab" }] }] }] }, + workspace_view: { device_id: "local", path: "/fixture", panel: "open", layout: { root: { area: { id: "a1", active: "d1", displays: ["d1", "d2"].map((id) => ({ id, kind: "browser", label: id, url: "about:blank", state: "open", tab_id: null })) } }, active_area: "a1", display_count: 2, limits }, agent_layout: { root: { split: { id: "s1", axis: "row", ratio: 0.5, first: { area: { id: "a1", active: "t1", displays: ["t1", "t2", "t3"].map((id) => ({ id })) } }, second: { area: { id: "a2", active: "outside", displays: [{ id: "outside" }] } } } }, active_area: "a1", canvases: {}, display_count: 4, limits } }, + } as unknown as SnapshotRest; +} +function draw(rest: SnapshotRest) { + const view = rest.workspace_view!; + const sizes = { areaMinWidth: 100, areaMinHeight: 100, divider: 4, tabStrip: 30 }; + for (const kind of ["agent", "view"] as const) { + const layout = kind === "agent" ? view.agent_layout! : view.layout!; + noteAreaFrame(kind, { workspace: { device_id: "local", path: "/fixture" }, layout, geometry: areaGeometry(layout.root, { x: 0, y: 0, width: 1200, height: 800 }, sizes), sizes } as never); + } + useShellStore.setState({ rest }); +} +const ids = (cycle: ReturnType) => cycle?.items.map((row) => row.target.kind === "surface" ? row.target.surface.id : "wrong-kind"); +const owner = { kind: "pane", workspace: "c", paneId: "t1-pane" } as const; + +describe("focused-area recent tabs", () => { + beforeEach(() => { resetRecent(); useUiStore.setState({ screen: { kind: "workspace" }, cycle: null }); noteAreaFrame("agent", null); noteAreaFrame("view", null); }); + it("uses exact Agent membership and MRU despite colliding area IDs and other checkouts", () => { + const rest = world(); draw(rest); + const checkout = rest.navigator!.workspaces![0]!.checkouts[0]!; + observeEntries(rest, tabSurface(checkout, "t2")); + observeEntries(rest, tabSurface(checkout, "outside")); + observeEntries(rest, tabSurface(checkout, "t3")); + expect(ids(areaCycle(rest, owner))).toEqual(["t1", "t3", "t2"]); + expect(ids(areaCycle(rest, { kind: "agent", workspace: "c", areaId: "a1" }))).toEqual(["t1", "t3", "t2"]); + expect(ids(areaCycle(rest, { kind: "view", workspace: "c", areaId: "a1" }))).toEqual(["d1", "d2"]); + }); + it("commits exactly one in-place selection and never dispatches a preview", () => { + const rest = world(); draw(rest); + const sent: unknown[] = []; + const actions = createActions((event) => { sent.push(event); }); + const cycle = areaCycle(rest, owner)!; + expect(sent).toEqual([]); + commitCycle(cycle, actions); + expect(sent).toEqual([]); + commitCycle({ ...cycle, index: 1 }, actions); + expect(sent).toEqual([expect.objectContaining({ kind: "focus_tab", payload: expect.objectContaining({ tab_id: "t2", in_place: true }) })]); + sent.length = 0; + const views = areaCycle(rest, { kind: "view", workspace: "c", areaId: "a1" })!; + commitCycle({ ...views, index: 1 }, actions); + expect(sent).toEqual([expect.objectContaining({ kind: "view_layout", payload: expect.objectContaining({ action: "focus", display_id: "d2" }) })]); + }); + it("prunes a moved tab using the new snapshot, keeps the frozen order and cancels a removed origin", () => { + const rest = world(); draw(rest); + const held = { ...areaCycle(rest, owner)!, index: 1 }; + const root = rest.workspace_view!.agent_layout!.root; + if (!("split" in root)) throw new Error("fixture split missing"); + root.split.first = { area: { id: "a1", active: "t1", displays: [{ id: "t1" }, { id: "t3" }] } }; + expect(ids(reconcileHeldCycle(held, rest))).toEqual(["t1", "t3"]); + expect(reconcileHeldCycle(held, rest)?.index).toBe(1); + root.split.first = { area: { id: "new-area", active: "t1", displays: [{ id: "t1" }, { id: "t3" }] } }; + expect(reconcileHeldCycle(held, rest)).toBeNull(); + }); + it("never falls back from a tool, outside owner, Overview, hidden View or delegated canvas", () => { + const rest = world(); draw(rest); + expect(areaCycle(rest, { kind: "tool", workspace: "c" })).toBeNull(); + expect(areaCycle(rest, { kind: "view", workspace: "other", areaId: "a1" })).toBeNull(); + useUiStore.setState({ screen: { kind: "main" } }); + expect(areaCycle(rest, owner)).toBeNull(); + useUiStore.setState({ screen: { kind: "workspace" } }); + rest.workspace_view!.panel = "closed"; + expect(areaCycle(rest, { kind: "view", workspace: "c", areaId: "a1" })).toBeNull(); + rest.workspace_view!.agent_layout!.canvases.a1 = "outside"; + expect(focusedCycleScope(rest, { kind: "pane", workspace: "c", paneId: "outside-pane" })?.areaId).toBe("a2"); + expect(focusedCycleScope(rest, owner)).toBeNull(); + }); +}); diff --git a/web/src/areaCycle.ts b/web/src/areaCycle.ts new file mode 100644 index 0000000000..87c560b8e8 --- /dev/null +++ b/web/src/areaCycle.ts @@ -0,0 +1,69 @@ +// Focused-area cycling narrows the existing page MRU to one exact drawn area. +// No second history or committed selection lives here. +import { areaFrame } from "./areaFrames"; +import { areasOf, findArea } from "./areaLayout"; +import { displaySurface, panelItem, recentEntries, tabSurface, type CycleItem, type Surface } from "./recent"; +import { frontCheckout, type SnapshotRest } from "./snapshot"; +import { workspaceViewOf } from "./workspace"; +import { useUiStore, type Cycle } from "./ui"; +import { keyboardOwner, type KeyboardOwner } from "./viewFocus"; + +export type CycleScope = { deviceId: string; checkoutId: string; path: string; kind: "agent" | "view"; areaId: string }; + +/** The owner must belong to the front checkout and an area actually drawn. */ +export function focusedCycleScope(rest: SnapshotRest | null, owner: KeyboardOwner = keyboardOwner()): CycleScope | null { + const checkout = frontCheckout(rest); + if (!checkout || owner.kind === "none" || owner.kind === "tool" || owner.workspace !== checkout.id || useUiStore.getState().screen?.kind !== "workspace") return null; + const kind = owner.kind === "view" ? "view" : "agent"; + const frame = areaFrame(kind); + if (!frame || frame.workspace.path !== checkout.path) return null; + let areaId = owner.kind === "view" || owner.kind === "agent" ? owner.areaId : undefined; + if (owner.kind === "pane") { + areaId = areasOf(frame.layout.root).find((area) => { + // A delegated canvas is not a member of the area's normal tab strip. + const shown = kind === "agent" ? areaFrame("agent")?.layout.canvases[area.id] ?? area.active : area.active; + return area.displays.some((item) => item.id === shown) && checkout.tabs.find((tab) => tab.id === shown)?.panes.some((pane) => pane.id === owner.paneId); + })?.id; + } + if (!areaId || !frame.geometry.areas.some((area) => area.id === areaId)) return null; + return { deviceId: frame.workspace.device_id, checkoutId: checkout.id, path: checkout.path, kind, areaId }; +} + +/** Null means the originating scope disappeared, never permission to widen it. */ +export function scopedSurfaces(rest: SnapshotRest | null, scope: CycleScope): { surfaces: Surface[]; active: string | null } | null { + const checkout = frontCheckout(rest); + const frame = areaFrame(scope.kind); + if (!checkout || checkout.id !== scope.checkoutId || checkout.path !== scope.path || !frame || frame.workspace.device_id !== scope.deviceId || frame.workspace.path !== scope.path || useUiStore.getState().screen?.kind !== "workspace") return null; + const view = workspaceViewOf(rest); + if (!view || view.device_id !== scope.deviceId || view.path !== scope.path || (scope.kind === "view" && view.panel === "closed")) return null; + const layout = scope.kind === "view" ? view.layout : scope.deviceId === "local" ? view.agent_layout : frame.layout; + if (!layout) return null; + const area = findArea(layout.root, scope.areaId); + if (!area || !frame.geometry.areas.some((box) => box.id === scope.areaId)) return null; + const surfaces = scope.kind === "agent" + ? area.displays.filter((item) => checkout.tabs.some((tab) => tab.id === item.id)).map((item) => tabSurface(checkout, item.id, scope.deviceId)) + : area.displays.map((item) => ({ ...displaySurface(checkout, item as import("./snapshot").ViewDisplaySnapshot), deviceId: scope.deviceId })); + return { surfaces, active: area.active }; +} + +export function focusedSurface(rest: SnapshotRest | null, scope: CycleScope | null): Surface | null { + const membership = scope && scopedSurfaces(rest, scope); + return membership ? membership.surfaces.find((surface) => surface.id === membership.active) ?? null : null; +} + +export function areaCycle(rest: SnapshotRest | null, owner?: KeyboardOwner): Cycle | null { + const scope = focusedCycleScope(rest, owner); + const membership = scope && scopedSurfaces(rest, scope); + if (!scope || !membership || membership.surfaces.length < 2) return null; + const current = membership.surfaces.find((surface) => surface.id === membership.active); + if (!current) return null; + const known = new Map(membership.surfaces.map((surface) => [surface.key, surface])); + const order = [current, ...recentEntries().flatMap((entry) => { + const surface = known.get(entry.key); + return surface && surface.key !== current.key ? [surface] : []; + })]; + const ordered = new Set(order.map((surface) => surface.key)); + order.push(...membership.surfaces.filter((surface) => !ordered.has(surface.key))); + const items = order.map((surface) => panelItem(rest, surface)).filter((item): item is CycleItem => item !== null); + return items.length > 1 ? { kind: "area", scope, originKey: current.key, items, index: 0 } : null; +} diff --git a/web/src/gallery/AreaFocusScene.tsx b/web/src/gallery/AreaFocusScene.tsx new file mode 100644 index 0000000000..a4012f707f --- /dev/null +++ b/web/src/gallery/AreaFocusScene.tsx @@ -0,0 +1,41 @@ +// The real area renderer and View tabs, with a bounded read-only content +// fixture for the focus design comparison. Native pages are verified in the app. +import { useEffect, useMemo } from "react"; +import { createActions } from "../actions"; +import { createAreaTree, type AreaAdapter } from "../AreaTree"; +import { TooltipProvider } from "../components/ui/tooltip"; +import type { ViewDisplaySnapshot, ViewLayoutSnapshot } from "../snapshot"; +import { DisplayTab } from "../ViewAreas"; +import { installKeyboardOwner, noteKeyboardOwner, useKeyboardOwner } from "../viewFocus"; +import { VIEW_WORDS } from "../viewLayout"; + +const Tree = createAreaTree("view"); +const CONTENT = "# 한글 노트\n\n현재 입력을 받는 영역만 강조합니다.\n다른 영역의 원래 선택과 내용은 읽을 수 있습니다.\n\nfixture % echo 한글 확인\n한글 확인"; + +export function AreaFocusScene({ theme }: { theme: "light" | "dark" }) { + const owner = useKeyboardOwner(); + const actions = useMemo(() => createActions(() => {}), []); + const layout = useMemo(() => { + const area = (id: string) => ({ id, active: `${id}-1`, displays: ["한글 노트.md", "검증 결과.md"].map((label, i) => ({ id: `${id}-${i + 1}`, label, kind: "file", state: "open", tab_id: null, preview: false, path: `/fixture/${label}` }) as ViewDisplaySnapshot) }); + return { root: { split: { id: "s1", axis: "row", ratio: 0.5, first: { area: area("a1") }, second: { area: area("a2") } } }, active_area: "a1", display_count: 4, limits: { areas: 6, depth: 5, displays: 64 } }; + }, []); + useEffect(() => { + document.documentElement.classList.toggle("dark", theme === "dark"); + document.documentElement.classList.toggle("light", theme === "light"); + const remove = installKeyboardOwner(); + noteKeyboardOwner({ kind: "view", workspace: "fixture", areaId: "a1" }); + return remove; + }, [theme]); + const adapter: AreaAdapter = { + words: VIEW_WORDS, + keyboardArea: owner.kind === "view" && owner.workspace === "fixture" ? owner.areaId : null, + label: (item) => item.label, + sameContent: (a, b) => a.path === b.path, + tab: (item, interaction) => , + body: () =>