Polishes your prompt for the model before you send it, and shows it next to the original

<h1 align="center">Prompt Polish: Claude Code mod</h1>
<b>Prompt Polish 는 모델별 공식 프롬프팅 가이드를 기준으로,<br> 직접 작성한 프롬프트를 Claude Code 안에서 바로 프롬프트 엔지니어링해 주는 Claude Code mod 입니다.</b>
<i>A Claude Code mod that rewrites your prompt with prompt engineering before you send it,<br> using the official prompting guide for the session's model.</i>
<b>한국어</b> · <a href="README.en.md">English</a>
<a href=".claude-plugin/plugin.json"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fraw.githubusercontent.com%2Fjheroorehj%2Fprompt-polish%2Fmain%2F.claude-plugin%2Fplugin.json&query=%24.version&prefix=v&label=version&color=blue" alt="플러그인 버전"></a> <a href="#요구-사항"><img src="https://img.shields.io/badge/Claude%20Code-2.1.287%2B-d97757" alt="Claude Code 2.1.287 이상"></a> <a href="https://github.com/jheroorehj/prompt-polish/stargazers"><img src="https://img.shields.io/github/stars/jheroorehj/prompt-polish?style=flat" alt="GitHub stars"></a>
<a href="#설치"><ruby><img src="docs/images/nav-install.svg" width="15%" alt="설치"></ruby></a> <a href="#왜-필요한가"><ruby><img src="docs/images/nav-why.svg" width="15%" alt="왜 필요한가"></ruby></a> <a href="#동작-방식"><ruby><img src="docs/images/nav-how.svg" width="15%" alt="동작 방식"></ruby></a> <a href="#사용법"><ruby><img src="docs/images/nav-usage.svg" width="15%" alt="사용법"></ruby></a> <a href="#명령어"><ruby><img src="docs/images/nav-commands.svg" width="15%" alt="명령어"></ruby></a> <a href="#설정"><ruby><img src="docs/images/nav-settings.svg" width="15%" alt="설정"></ruby></a> <a href="#자주-묻는-질문"><ruby><img src="docs/images/nav-faq.svg" width="15%" alt="자주 묻는 질문"></ruby></a> <a href="#개발"><ruby><img src="docs/images/nav-develop.svg" width="15%" alt="개발"></ruby></a> <a href="#참고한-자료"><ruby><img src="docs/images/nav-references.svg" width="15%" alt="참고한 자료"></ruby></a> <a href="#피드백"><ruby><img src="docs/images/nav-feedback.svg" width="15%" alt="피드백"></ruby></a> <a href="#라이선스"><ruby><img src="docs/images/nav-license.svg" width="15%" alt="라이선스"></ruby></a> <a href="https://github.com/jheroorehj/prompt-polish"><ruby><img src="docs/images/nav-logo.svg" width="15%" alt="Prompt Polish @jheroorehj, GitHub 저장소에서 스타 누르기"></ruby></a>
/plugin marketplace add jheroorehj/prompt-polish
/plugin install prompt-polish@prompt-polish
<img src="docs/images/hero.svg" width="820" alt="터미널에서 /p_polish 를 입력해 창을 열고, 프롬프트를 쓰고 Enter 를 누르면 Polishing 애니메이션이 돌다가 Original Prompt 와 Polished Prompt 가 표시되고, Apply Polish 를 누르면 입력창이 재작성한 프롬프트로 바뀌며, Enter 를 한 번 더 누르면 그 프롬프트가 대화에 전송되는 과정을 보여 주는 움직이는 그림"> <sub>터미널의 창: 프롬프트 입력 → 재작성 결과 확인 → <code>Apply Polish</code> → Enter 로 전송</sub>
재작성은 두 가지로 쓸 수 있습니다.
AUTO ON 에서 Enter: 프롬프트를 쓰고 Enter 를 누르면 별도의 모델 호출로 프롬프트를 먼저 재작성하고, 결과를 Claude Code 의 질문 상자로 보여 주며 Apply Polish · Keep Original · Retry Polish 중에서 묻습니다. 고르는 즉시 그 프롬프트가 전송되므로 Enter 를 한 번 더 누를 필요가 없고, 대화에 "훅에 의해 차단된 프롬프트" 기록도 남지 않습니다.Prompt Polish 버튼(또는 /p_polish <프롬프트>): 창에 원본(Original Prompt)과 재작성 결과(Polished Prompt)가 표시되고, Apply Polish 를 누르면 입력창의 내용이 재작성 결과로 교체됩니다. Enter 를 눌러 직접 전송합니다.위 그림은 터미널의 창에서 결과를 확인하고 적용하는 단계입니다. 이 단계는 Prompt Polish 버튼으로 재작성할 때의 흐름과 같습니다. 그림을 만든 뒤 AUTO ON 이 바뀌어서, 지금은 Enter 로 재작성하면 결과를 창 대신 질문 상자로 묻고 고르는 즉시 전송합니다. 아래 그림은 Claude 데스크톱 앱에서 AUTO ON 으로 Enter 를 눌렀을 때의 흐름입니다.
<img src="docs/images/desktop-auto.svg" width="820" alt="Claude 데스크톱 앱에서 입력창에 프롬프트를 쓰고 Enter 를 누르면 프롬프트가 대화에 올라가고, 입력창 위 띠의 상태가 Polishing 으로 바뀌며 도는 링과 점선이 움직입니다. 재작성이 끝나면 상태가 Review 가 되고 띠에 Waiting for your answer 가 표시되며, 재작성한 글을 보여 주는 질문과 Apply Polish, Keep Original, Retry Polish 선택지가 나옵니다. Apply Polish 를 고르면 재작성한 글이 대화에 전송되고 띠는 Ready 로 돌아오는 과정을 보여 주는 움직이는 그림"> <sub>데스크톱 앱, <code>AUTO ON</code>: Enter → <code>Polishing</code> → 질문에서 <code>Apply Polish</code> 선택 → 재작성한 글이 전송됩니다. 질문 상자의 모양은 앱이 정하므로 그림은 개략입니다.</sub>
mod 는 훅 모듈을 가진 Claude Code 플러그인이라, 다른 플러그인처럼 /plugin 명령으로 설치합니다.
Claude Code 안에서 아래 두 줄을 입력합니다.
/plugin marketplace add jheroorehj/prompt-polish
/plugin install prompt-polish@prompt-polish
터미널에서 설치하려면 아래 명령을 실행합니다.
claude plugin marketplace add jheroorehj/prompt-polish
claude plugin install prompt-polish@prompt-polish
설치 후 새 세션을 열고 /p_polish 를 입력하면 창이 열립니다.
git clone https://github.com/jheroorehj/prompt-polish
claude --plugin-dir ./prompt-polish
이렇게 실행한 세션에서만 mod 가 로드됩니다.
| 항목 | 설명 |
|---|---|
| Claude Code 2.1.287 이상 | mods 를 지원하는 버전입니다. claude --version 으로 확인합니다. |
| 전체화면 터미널 (권장) | 창이 대화 옆에 도킹되고 버튼을 마우스로 클릭할 수 있습니다. 일반 화면에서는 창이 입력창 위에 요약 형태로 표시되고 키보드로만 조작합니다. |
| Claude 데스크톱 앱 (Code 탭) | 데스크톱 앱 전용 화면으로 그려집니다. 기본은 입력창 바로 위 띠이고, Placement 설정으로 대화 옆 패널만 쓸 수도 있습니다. 구성과 그림은 8. Claude 데스크톱 앱에서 에 있습니다. 1~7번의 그림과 표는 터미널 화면 기준이며, 버튼 이름과 동작은 같습니다. |
| VS Code 확장 프로그램 · 모바일 앱 | 터미널과 같은 칸 기반 창으로 그려집니다. |
Claude Code 에 보내는 프롬프트는 생각나는 순서대로 적어 그대로 보내게 되기 쉽습니다. 프롬프트 엔지니어링을 적용하려면 Claude 를 따로 열어 프롬프트를 맡기고, 돌려받은 결과를 복사해 와야 합니다. 프롬프트를 보낼 때마다 이 과정을 반복하는 것은 번거롭고, 따로 연 Claude 에는 작업 중인 프로젝트와 직전 대화가 전달되지 않습니다.
Prompt Polish 는 이 과정을 Claude Code mod 로 만들어 터미널과 Claude 데스크톱 앱 안에 넣은 것입니다. 입력창에서 Enter 를 누르면 재작성이 실행되고, 결과는 질문 상자나 같은 화면의 창에 표시됩니다. 재작성 호출에는 프로젝트 파일과 에이전트의 마지막 답변이 함께 전달됩니다.
모델마다 맞는 프롬프팅 방식이 다르다는 점도 반영했습니다. 현재 세션의 모델을 확인해서 그 모델에 해당하는 가이드를 적용하고, 다른 모델에 보낼 프롬프트라면 가이드를 직접 고를 수 있습니다.
| 항목 | 동작 |
|---|---|
| 전송 전 확인 | AUTO ON 상태에서 Enter 를 누르면 프롬프트가 대화에 올라간 채로 재작성부터 하고, 결과를 질문 상자로 물은 뒤 고른 쪽을 전송합니다. 프롬프트를 막지 않고 훅 안에서 기다렸다가 통과시키는 방식이라 Enter 를 다시 누를 필요가 없습니다. 재작성이 실패했거나 이미 명확하거나 질문을 할 수 없는 환경이면 쓴 그대로 전송합니다. Stop 으로 멈추거나 질문 상자를 닫으면 전송하지 않습니다. 재작성이 도는 중에 Enter 를 또 누르면 그 프롬프트는 전송되지 않습니다. |
| 가이드 선택 | Opus 5.5, Sonnet 5.5, GPT-6 Astra, GPT-5.6 가이드가 내장되어 있습니다. 세션 모델 ID 에 sonnet 이 있으면 Sonnet 5.5, gpt-6 또는 astra 가 있으면 GPT-6 Astra, gpt-5 가 있으면 GPT-5.6 가이드를 쓰고, 그 외에는 Opus 5.5 가이드를 씁니다. |
| 가이드 적용 | 가이드마다 "보강할 것"과 "지우거나 바꿀 것" 목록이 있습니다. 예를 들어 Opus 5.5 가이드는 완료 기준을 명시하게 하고 "think step by step" 같은 문구를 지웁니다. |
| 유지하는 것 | 프롬프트의 의도, 범위, 언어, 말투는 유지합니다. 파일 경로, 코드, 명령어, URL, @멘션, 인용문은 글자 그대로 둡니다. 원본에 없는 요구사항이나 파일을 추가하지 않습니다. |
재작성은 작업 세션과 분리된 모델 호출 한 번으로 처리합니다. 도구 없이 텍스트만 주고받는 호출이고, 이전 호출의 내용은 이어받지 않습니다. 요청과 응답은 작업 중인 대화에 추가되지 않고, 결과는 창이나 질문 상자에만 표시됩니다. 작업 세션에 영향을 주는 것은 두 가지뿐입니다. Prompt Polish 버튼으로 재작성했다면 Apply Polish 를 눌렀을 때의 입력창 내용이고, AUTO ON 이라면 질문 상자에서 고른 글이 전송되는 것입니다.
호출에는 아래 네 가지가 전달됩니다. 대화 기록 전체는 전달하지 않습니다.
| 전달되는 것 | 내용 |
|---|---|
| 프로젝트 파일 | 파일 목록, CLAUDE.md, 매니페스트, 그리고 프롬프트에 이름이 나온 파일의 앞부분입니다. 자세한 내용은 아래 표에 있습니다. |
| 원본 프롬프트 | 입력창에 쓴 프롬프트 전체입니다. 재작성 대상으로 전달됩니다. |
| 마지막 답변 | 작업 세션에서 에이전트가 마지막으로 한 답변의 텍스트입니다. 4,000자를 넘으면 끝의 4,000자만 전달합니다. "방금 말한 것" 같은 지시어를 풀어 쓰는 용도입니다. |
| 모델별 가이드 | Session Model 에 해당하는 가이드의 "보강할 것"과 "지우거나 바꿀 것" 목록입니다. 공통 편집 규칙과 함께 시스템 프롬프트로 전달됩니다. |
Retry Polish 를 누르면 여기에 방금 결과가 추가로 전달됩니다. 그와 다른 구성으로 쓰게 하는 용도입니다.
프로젝트 파일은 mod 가 디스크에서 직접 읽어서 텍스트로 넣습니다. 재작성 모델이 파일을 열어 보는 것이 아니므로, 아래에 적힌 것만 전달됩니다.
| 프로젝트 파일 | 읽는 방법 |
|---|---|
| 파일 목록 | 프로젝트 루트에서 git ls-files 로 추적 중인 파일과, 무시되지 않은 미추적 파일의 경로를 가져옵니다. git 저장소가 아니면 폴더를 3단계까지 탐색합니다(node_modules, dist 등 제외, 최대 2,000개). 파일이 150개 이하면 경로를 전부 적고, 넘으면 루트 근처 파일만 이름으로 적고 나머지는 폴더별 개수로 적습니다. |
CLAUDE.md | 프로젝트 루트에 있으면 앞 2,000자를 넣습니다. |
| 매니페스트 | package.json, go.mod, pyproject.toml, Cargo.toml 등 기술 스택을 알 수 있는 파일이 루트에 있으면 2개까지, 각각 앞 1,500자를 넣습니다. |
| 이름이 나온 파일 | 원본 프롬프트나 마지막 답변에 경로 또는 파일 이름이 적힌 파일을 3개까지, 각각 앞 2,000자를 넣습니다. 같은 이름의 파일이 여러 개면 경로까지 적어야 찾습니다. |
[!NOTE]
.env, 키와 인증서 파일, 이름에secret이나credential이 들어간 파일, 이미지와 압축 파일 같은 바이너리는 내용을 읽지 않습니다. 파일 목록에는 이름만 들어갑니다.
토큰 사용량을 줄이기 위해 입력을 아래처럼 다룹니다.
| 동작 | 입력 처리 |
|---|---|
Polish 실행 (Prompt Polish 버튼, AUTO ON 에서 Enter, /p_polish <프롬프트>) | 프로젝트 파일과 마지막 답변을 새로 읽고, 읽은 내용을 보관합니다. |
Retry Polish | 디스크를 다시 읽지 않고 보관한 내용을 그대로 다시 보냅니다. 원본 프롬프트와 이전 결과만 새로 붙습니다. 입력창의 프롬프트를 고쳐 쓴 경우에만 이름이 나온 파일을 다시 찾아 읽습니다. |
Apply Polish | 보관한 내용을 버립니다. |
Keep Original, Stop, 호출 실패, 프롬프트 전송 | 보관한 내용을 버리지 않습니다. 다음 Polish 실행 때 새로 읽은 내용으로 교체됩니다. |
요청은 잘 바뀌지 않는 것부터 순서대로 구성합니다. 가이드, 프로젝트(파일 목록·CLAUDE.md·매니페스트), 이름이 나온 파일과 마지막 답변, 원본 프롬프트 순서입니다. 앞의 세 부분에는 각각 프롬프트 캐시 표시를 붙입니다. 프로젝트 부분은 파일 구성이 그대로면 매번 같은 텍스트가 되도록 정렬해서 만듭니다.
Opus 5.5 와 Sonnet 5.5 가이드는 참고한 자료의 Anthropic 공식 문서를 읽고, 프롬프트를 고칠 때 적용할 수 있는 항목을 규칙으로 정리한 것입니다. 문서를 실행 중에 가져오지는 않고, 정리한 규칙이 hooks/guides.ts 에 들어 있습니다. GPT-6 Astra 와 GPT-5.6 가이드에는 아직 출처 문서를 반영하지 않았습니다.
1. 창 열기 · 2. 프롬프트 재작성하고 보내기 · 3. 다시 재작성하기 · 4. 적용 취소하기 · 5. AUTO 와 가이드 확인 · 6. 모델 선택 · 7. 기록과 단축키 · 8. Claude 데스크톱 앱에서
/p_polish 를 입력합니다. /polish 도 같은 명령입니다. Open on start 설정이 켜져 있으면(기본값) 세션을 시작할 때 창이 자동으로 열립니다. 데스크톱 앱에서 Placement 가 band(기본값)이면 창은 열리지 않고 띠가 입력창 위에 나와 있습니다.
<img src="docs/images/guide-ready.svg" width="410" alt="대기 상태의 Prompt Polish 창. 위에서부터 설정 박스, Prompt Polish 버튼, 맨 아래에 Keys 와 History 줄이 있다"> <sub>대기 상태의 창. 위에서부터 설정 박스, <code>Prompt Polish</code> 버튼, <code>Keys</code> · <code>History</code></sub>
| 위치 | 표시 | 설명 |
|---|---|---|
| 설정 박스 1행 왼쪽 | Reference : Opus 5.5 Guide | 현재 적용 중인 가이드입니다. 클릭하면 가이드 설명이 펼쳐집니다. |
| 설정 박스 1행 오른쪽 | Ready / Polishing / Review | 대기, 재작성 중, 결과 확인 대기 중 현재 상태입니다. |
| 설정 박스 2행 | AUTO ON / AUTO OFF | Enter 를 눌렀을 때 재작성을 먼저 할지 정합니다. |
| 설정 박스 2행 | Session Model : … | 프롬프트를 받을 모델입니다. 이 값에 따라 가이드가 정해집니다. |
| 설정 박스 3행 | Polish Model : … (…) | 재작성을 수행할 모델과 effort 입니다. |
| 설정 박스 아래 | Prompt Polish | 입력창에 있는 프롬프트를 지금 재작성합니다. |
| 맨 아래 | Keys · History | 단축키 목록과 작업 기록입니다. 클릭하면 위쪽으로 펼쳐집니다. |
이 표는 터미널 화면 기준입니다. 데스크톱 앱 화면은 8번에서 설명합니다.
AUTO ON 에서 Enter
| 순서 | 할 일 | 결과 |
|---|---|---|
| 1 | 입력창에 프롬프트를 쓰고 <kbd>Enter</kbd> | 프롬프트가 대화에 올라가고, 전송은 재작성이 끝날 때까지 기다립니다. |
| 2 | 대기 (중단하려면 Stop) | 상태가 Polishing 이 되고 스피너, 경과 시간, Polishing prompt 가 표시됩니다. |
| 3 | 질문 상자에서 선택 | 재작성한 글이 질문으로 나오고, 상태는 Review, 띠와 창에는 Waiting for your answer 가 표시됩니다. |
| 4 | Apply Polish / Keep Original / Retry Polish | 고르는 즉시 전송됩니다. Other 에 직접 쓴 글을 넣으면 그 글이 전송됩니다. |
| 선택 | 동작 |
|---|---|
Apply Polish | 재작성한 프롬프트를 전송합니다. 모델이 받고 대화에 기록되는 글은 재작성한 글입니다. |
Keep Original | 쓴 그대로 전송합니다. |
Retry Polish | 방금 결과를 함께 넘겨서, 그와 다른 구성으로 다시 재작성하고 다시 묻습니다. |
Other | 직접 쓴 글을 전송합니다. |
질문 상자를 닫으면(dismiss) 프롬프트는 전송되지 않습니다.
Prompt Polish 버튼 또는 /p_polish <프롬프트>
| 순서 | 할 일 | 결과 |
|---|---|---|
| 1 | 입력창에 프롬프트를 쓰고 Prompt Polish 버튼 | 재작성이 시작됩니다. |
| 2 | 대기 (중단하려면 Stop) | 설정 박스에 스피너, 경과 시간, Polishing prompt 가 표시됩니다. |
| 3 | 결과 확인 | Original Prompt 와 Polished Prompt 박스가 각각 글자 수와 함께 표시됩니다. |
| 4 | Apply Polish / Retry Polish / Keep Original 중 선택 | 아래 버튼 표를 참고합니다. |
| 5 | <kbd>Enter</kbd> | 입력창에 있는 프롬프트가 전송됩니다. |
<img src="docs/images/polishing.svg" width="410" alt="재작성 중인 설정 박스. 스피너와 경과 시간, Polishing prompt 글자, 좌우로 움직이는 선이 박스 안에 있고 그 아래 오른쪽에 Stop 이 있다"> <img src="docs/images/review.svg" width="410" alt="재작성이 끝난 화면. Original Prompt 박스와 Polished Prompt 박스가 있고, 그 아래에 Apply Polish, Retry Polish, Keep Original 버튼이 있다"> <sub>왼쪽: 2단계, 재작성 중 · 오른쪽: 3단계, 결과 확인 화면</sub>
| 버튼 | 동작 |
|---|---|
Apply Polish | 입력창의 내용을 재작성 결과로 교체합니다. |
Retry Polish | 방금 결과를 함께 넘겨서, 그와 다른 구성으로 다시 재작성합니다. |
Keep Original | 재작성 결과를 버립니다. 입력창이 비어 있으면 원본을 다시 채워 넣습니다. |
Stop | 진행 중인 재작성을 중단합니다. 재작성 중에만 표시됩니다. |
두 박스는 창 폭이 110칸 미만이면 위아래로, 110칸 이상이면 좌우로 배치됩니다.
아래 경우에는 AUTO ON 이어도 재작성이나 질문 없이 바로 전송합니다.
/, !, # 으로 시작하는 입력Already clear. No changes. 알림 표시)Polish failed. 알림 표시)A question cannot be asked here. 알림 표시)Prompt Polish 버튼으로 이미 결과를 확인한 프롬프트: 입력창의 글을 Enter 로 보낼 때 다시 재작성하지 않습니다.결과 확인 중에 창을 닫으면 Keep Original 과 같게 처리됩니다. 다만 데스크톱 앱에서 띠를 쓸 때는 옆 패널을 닫아도 결과 확인이 띠에 그대로 남습니다.
[!NOTE]
AUTO ON에서는 Enter 를 누르는 순간 프롬프트가 대화에 올라갑니다. 앱과 터미널은 프롬프트를 먼저 대화에 올린 뒤에야 mod 에 넘기므로, mod 가 그보다 앞서 가로챌 방법이 없습니다. 대신 프롬프트를 막지 않고 통과시키므로Prompt blocked by a hook기록은Stop으로 멈추거나 질문 상자를 닫았을 때만 남습니다. 이유는 자주 묻는 질문에 있습니다.
Retry Polish같은 프롬프트를 다시 재작성합니다. 이때 방금 결과를 모델에 함께 전달해서, 구성과 표현이 그와 다르게 나오도록 요청합니다. 프로젝트 파일과 마지막 답변은 다시 읽지 않고 처음 Polish 때 읽은 내용을 그대로 씁니다. 요청의 앞부분이 직전 호출과 같아서 그 부분은 프롬프트 캐시에서 읽힙니다. 횟수 제한은 없고, 실행할 때마다 History 에 Retried 가 한 줄 추가됩니다.
<img src="docs/images/retry.svg" width="820" alt="Review 화면에서 Retry Polish 를 누르면 설정 박스에 Polishing 애니메이션이 돌고, 끝나면 Polished Prompt 박스의 내용이 새 결과로 바뀌는 과정을 보여 주는 움직이는 그림"> <sub><code>Retry Polish</code> 를 누르면 <code>Polished Prompt</code> 가 새 결과로 교체됩니다</sub>
Retry Polish 로 만든 결과는 버전으로 쌓입니다. 버전이 둘 이상이면 버튼 줄 오른쪽 끝(데스크톱 앱에서는 띠의 무대 머리와 패널의 결과 카드 위)에 ‹ 2 / 3 › (데스크톱 앱에서는 ‹ Version 2 of 3 ›) 이 생기고, ‹ 와 › 로 앞뒤 버전을 넘겨볼 수 있습니다. Apply Polish 는 지금 보이는 버전을 적용하고, Retry Polish 는 지금 보이는 버전과 다르게 다시 재작성합니다. 버전은 최근 10개까지 남고, 새로 Prompt Polish 를 하거나 적용·전송하면 비워집니다. 위 그림은 이 표시가 생기기 전에 만든 것이라 그림에는 나오지 않습니다.
입력창에 글이 있으면 처음 재작성한 프롬프트가 아니라 현재 입력창의 글을 재작성합니다. 프롬프트를 고쳐 쓴 뒤 Retry Polish 를 누르면 Original Prompt 도 고쳐 쓴 글로 바뀝니다. 이 경우에는 고쳐 쓴 글에 이름이 나온 파일만 다시 찾아 읽고, 파일 목록·CLAUDE.md·매니페스트와 마지막 답변은 처음 읽은 내용을 그대로 씁니다.
<img src="docs/images/retry-edited.svg" width="820" alt="Review 화면에서 입력창에 남아 있는 프롬프트 끝에 한 문장을 덧붙인 뒤 Retry Polish 를 누르면, Polishing 애니메이션이 돌고 나서 Original Prompt 가 덧붙인 글로 바뀌고 Polished Prompt 에 그 내용이 반영된 새 결과가 나오는 과정을 보여 주는 움직이는 그림"> <sub>입력창의 프롬프트에 문장을 추가한 뒤 <code>Retry Polish</code> 를 누른 경우</sub>
Undo ApplyApply Polish 를 누르면 Prompt Polish 버튼 옆에 Undo Apply 가 생깁니다. 누르면 입력창이 적용 전 내용으로 돌아가고 버튼은 사라집니다. 프롬프트를 전송한 뒤에는 이 버튼이 표시되지 않습니다.
<img src="docs/images/undo.svg" width="820" alt="Apply Polish 를 누르면 입력창이 재작성한 프롬프트로 바뀌고 Prompt Polish 옆에 Undo Apply 가 생기며, Undo Apply 를 누르면 입력창이 원래 프롬프트로 돌아가고 버튼이 사라지는 과정을 보여 주는 움직이는 그림"> <sub><code>Apply Polish</code> 후 <code>Undo Apply</code> 를 누르면 입력창이 적용 전 내용으로 돌아갑니다</sub>
AUTO 와 가이드 확인<img src="docs/images/auto.svg" width="410" alt="AUTO ON 을 누르면 AUTO OFF 로 바뀌면서 바로 아래에 안내 박스가 잠깐 나타났다 사라지고, 다시 누르면 AUTO ON 으로 돌아오며 다른 안내가 나타나는 과정을 보여 주는 움직이는 그림"> <img src="docs/images/reference.svg" width="410" alt="Reference : Opus 5.5 Guide 머리글을 누르면 그 아래에 가이드를 설명하는 박스가 열리고, 다시 누르면 닫히는 과정을 보여 주는 움직이는 그림"> <sub>왼쪽: <code>AUTO</code> 전환 · 오른쪽: <code>Reference</code> 를 눌러 가이드 설명 열기</sub>
| 표시 | 동작 |
|---|---|
AUTO ON | Enter 를 누르면 재작성부터 하고, 결과를 질문 상자로 물은 뒤 고른 쪽을 전송합니다. |
AUTO OFF | Enter 를 누르면 바로 전송합니다. 재작성이 필요할 때만 Prompt Polish 버튼을 누르면 되고, 이후 과정은 2번의 3단계부터와 같습니다. |
Reference : … | 클릭하면 현재 가이드가 무엇을 보강하고 무엇을 지우는지 요약한 설명이 펼쳐집니다. 다시 클릭하면 닫힙니다. |
터미널에서는 AUTO 를 전환하면 버튼 아래에 Enter 의 동작을 설명하는 안내가 5초 동안 표시됩니다. 데스크톱 앱의 옆 패널은 Settings 를 펼치면 AUTO 줄 아래에 같은 설명이 있고, 띠에는 이 설명이 없습니다. 설정은 저장되어 다음 세션에도 유지됩니다.
<img src="docs/images/session-model.svg" width="410" alt="Session Model 버튼을 누르면 다섯 항목의 목록이 열리고, GPT-6 Astra 를 고르면 머리글이 Reference : GPT-6 Astra Guide 로 바뀌며 창의 테두리와 강조 버튼이 초록이 되고, 다시 목록에서 Opus 5.5 (Detected) 를 고르면 원래대로 돌아오는 과정을 보여 주는 움직이는 그림"> <img src="docs/images/polish-model.svg" width="410" alt="Polish Model 버튼을 누르면 왼쪽에 모델 목록, 오른쪽에 다섯 눈금의 Effort 슬라이더가 있는 박스가 열리고, 목록에서 opus 를 고르고 슬라이더에서 high 를 고르는 동안 버튼의 글자가 따라 바뀌며, done 을 누르면 박스가 닫히는 과정을 보여 주는 움직이는 그림"> <sub>왼쪽: <code>Session Model</code> 목록 · 오른쪽: <code>Polish Model</code> 과 effort 선택</sub>
Session Model 은 프롬프트를 받을 모델입니다.
(Detected) 가 붙습니다.Reference 의 가이드 이름이 함께 바뀝니다.Polish Model 은 재작성을 수행할 모델입니다.
> 와 ✓ 로 표시되고 목록 맨 위에 놓입니다.low, medium, high, xhigh, max)을 클릭합니다.done 을 누르면 닫힙니다.두 값 모두 저장되어 다음 세션에도 유지됩니다.
데스크톱 앱에서는 Session, Polish, Effort 가 각각 선택이고, 목록은 칩으로 펼쳐지며 하나를 고르면 닫힙니다. 목록에 모델이 15개를 넘으면 앞의 15개만 칩으로 보이고, 나머지는 /p_polish model <이름> 으로 고릅니다.
<img src="docs/images/keys-history.svg" width="410" alt="창 아래쪽에서 Keys 표와 History 목록을 펼친 모습"> <sub><code>Keys</code> 와 <code>History</code> 를 펼친 모습</sub>
History 에는 Polished(재작성), Retried(다시 재작성), Applied(적용), Kept(원본 유지), Failed(실패)가 시각과 함께 기록됩니다. 접어 두면 가장 최근 한 건만 옆에 표시되고, 펼치면 최근 8건이 표시됩니다.
Keys 는 단축키 목록입니다.
[!IMPORTANT] 단축키는 이 목록을 펼쳐 둔 동안에만 동작합니다. 창을 클릭하거나 <kbd>ctrl</kbd>+<kbd>x</kbd> <kbd>tab</kbd> 을 눌러 창에 포커스를 준 뒤 사용합니다.
| 키 | 동작 | 키 | 동작 |
|---|---|---|---|
| <kbd>p</kbd> | Prompt Polish | <kbd>a</kbd> | AUTO 전환 |
| <kbd>y</kbd> | Apply Polish | <kbd>t</kbd> | Session Model 목록 |
| <kbd>r</kbd> | Retry Polish | <kbd>m</kbd> | Polish Model 박스 |
| <kbd>x</kbd> | Keep Original | <kbd>1</kbd>-<kbd>9</kbd> | 열려 있는 목록에서 선택 |
| <kbd>u</kbd> | Undo Apply | <kbd>l</kbd> | History |
| <kbd>b</kbd> | 이전 버전 | <kbd>n</kbd> | 다음 버전 |
| <kbd>c</kbd> | Stop | <kbd>k</kbd> | Keys |
| <kbd>Tab</kbd> | 다음 버튼으로 이동 | <kbd>Enter</kbd> | 버튼 누르기 |
데스크톱 앱(Code 탭)은 같은 기능을 앱 전용 화면으로 그립니다. 모든 조작은 클릭이고, 컨트롤은 높이가 같은 둥근 박스이며, 글자뿐 아니라 아이콘·화살표·주변 여백 어디를 눌러도 눌립니다. 단축키 목록(Keys)은 없습니다.
띠 는 Placement 가 band(기본값)일 때의 화면으로, 입력창 바로 위에 놓입니다. 앱이 띠에 주는 높이는 약 11줄이고 넘친 내용은 스크롤바 없이 잘립니다. 그래서 띠는 그 안에 들도록 아래 네 자리로만 구성하고, 상태가 바뀌어도 각 자리는 그대로입니다.
| 자리 | 내용 |
|---|---|
| 머리 | 왼쪽에 이름과 화살표(▾), 오른쪽에 AUTO 와 상태입니다. 이름을 누르면 띠가 줄어듭니다. Ready 는 움직이지 않는 점, Polishing 은 도는 링, Review 는 천천히 움직이는 점입니다. |
| 설정 | Session·Polish·Effort 선택입니다. 폴리시 중에는 선택 대신 지금 쓰는 값이 같은 자리에 표시됩니다. |
| 무대 | 폴리시 중에는 로딩 표시, 결과 확인에서는 재작성한 글의 앞 두 줄과 버전(‹ Version 2 of 3 ›)입니다. AUTO ON 으로 질문 상자의 답을 기다리는 동안에는 Waiting for your answer 가 표시됩니다. |
| 맨 아래 | 왼쪽은 지금 할 일입니다(Prompt Polish 와 Undo Apply, 결과 확인의 Apply Polish·Retry Polish·Keep Original, 실행 중에는 Stop). 오른쪽은 Full view(결과 확인에서만)와 History 입니다. |
<img src="docs/images/desktop-band.svg" width="820" alt="입력창 위 띠의 세 가지 상태를 위에서부터 쌓은 그림. 대기 상태는 이름과 AUTO 스위치와 Ready, 세 선택과 Prompt Polish 버튼과 History 만 있습니다. 재작성 중에는 상태가 Polishing 이고 선택 자리에 지금 쓰는 값이 흐리게 표시되며, 무대에 Polishing prompt 와 점선이 있고 맨 아래에 Stop 이 있습니다. 결과 확인에서는 상태가 Review 이고, 무대에 재작성한 글의 앞부분이 있으며, 맨 아래에 Apply Polish, Retry Polish, Keep Original 과 오른쪽에 Full view, History 가 있습니다."> <sub>띠의 세 상태. 위에서부터 대기 · 재작성 중 · 결과 확인 (<code>Prompt Polish</code> 버튼으로 재작성한 경우)</sub>
AUTO ON 에서 Enter 를 누르면 재작성하는 동안 띠가 Polishing 이 되고, 끝나면 Review 가 되면서 무대에 Waiting for your answer 가 표시됩니다. 결과는 띠가 아니라 질문 상자로 묻고, 이때 맨 아래 줄의 왼쪽에는 누를 것이 없습니다. 질문 상자의 모양은 앱이 정합니다.
선택 목록이 열려 있는 동안에는 목록이 무대와 맨 아래 줄 자리를 대신하고, 하나를 고르면 닫힙니다.
<img src="docs/images/desktop-model.svg" width="820" alt="Polish 선택을 열면 아래에 모델 이름이 칩으로 늘어서고 사용 중인 sonnet 에는 체크 표시와 강조 테두리가 있습니다. 그 아래의 띠에서는 Effort 선택을 열면 low, medium, high, xhigh, max 칩이 나오고 low 가 사용 중입니다."> <sub>선택 목록은 칩으로 펼쳐집니다. 위: <code>Polish</code> · 아래: <code>Effort</code></sub>
이름(Prompt Polish ▾)을 누르면 띠가 줄어듭니다. 줄인 띠는 입력창 위에 아무것도 남기지 않고, 입력창 아래 줄 오른쪽에 작은 칩 하나가 생깁니다. 칩의 글자와 점이 상태를 보여 주고(대기는 Prompt Polish 와 초록 점, 재작성 중은 Polishing… 과 주황 점, 결과 확인은 Review 와 파란 점), 칩을 누르면 띠가 다시 펼쳐집니다. 줄여 두어도 AUTO ON 은 그대로 동작하고, 마지막에 둔 상태는 다음 세션에도 유지됩니다.
긴 재작성 결과는 띠에서 다 읽을 수 없으므로 옆 패널 에서 읽습니다. 결과 확인이 시작되면 패널이 자동으로 열려 원본과 재작성한 글 전체, 버전 넘기기, 적용·재시도·유지 버튼을 보여 주고, 적용하거나 유지하거나 프롬프트를 전송하면 닫힙니다. Full view 는 패널을 다시 열고, History 는 기록을 펼친 패널을 엽니다.
옆 패널 은 Placement 가 pane 일 때 이것만 사용합니다. 카드가 위에서 아래로 쌓입니다.
<img src="docs/images/desktop-pane.svg" width="820" alt="대화 오른쪽에 옆 패널이 열린 그림. 위에서부터 이름과 Review 상태와 네 단계(Draft, Polish 는 완료, Review 는 진행 중, Apply 는 대기)가 있는 카드, Version 2 of 3 과 재작성한 글 전체와 Show original 줄과 Apply Polish, Retry Polish, Keep Original 버튼이 있는 결과 카드, 접힌 Settings 카드, 접힌 History 카드가 쌓여 있습니다. 대화 아래의 입력창에는 아직 원본 프롬프트가 들어 있습니다."> <sub>옆 패널의 결과 확인. 띠를 쓰는 경우에는 <code>Full view</code> 로 같은 패널이 열립니다.</sub>
| 카드 | 내용 |
|---|---|
| 진행 | 이름과 상태, 그 아래에 Draft·Polish·Review·Apply 네 단계가 표시됩니다. 대기 중에는 Prompt Polish 버튼, 폴리시 중에는 로딩 표시와 Stop 이 있습니다. |
| 결과 | 결과 확인에서만 나옵니다. 재작성한 글 전체, Show original 로 펼치는 원본, Apply Polish·Retry Polish·Keep Original 입니다. |
Settings | 접힌 상태에서는 현재 설정을 한 줄로 보여 줍니다. 펼치면 AUTO, Session model, Polish model, Effort(low~max 다섯 칸), 가이드가 있습니다. |
History | 접은 상태에서는 가장 최근 한 건을 옆에 보여 주고, 펼치면 최근 8건을 보여 줍니다. |
버튼이 눌리지 않으면 자주 묻는 질문의 클릭 받이 항목을 확인합니다.
새 세션이나 /clear 뒤에 앞서 하던 일을 이어가는 기능입니다. 모두 사용자가 각자 켜거나 고르며, 아무것도 저절로 붙지 않습니다.
TRAIL 버튼이나 /p_polish carry on 으로 켭니다. 기본값은 꺼짐입니다. 켜면 프로젝트마다 최근 프롬프트 8개, 마지막 답변의 끝, 바꾼 파일 이름, 할 일 목록, git status 를 이 컴퓨터의 Claude 폴더 안 플러그인 저장소에만 기록합니다. 모델은 부르지 않습니다. API 키, 토큰, 비밀번호, 이메일, 전화번호, 주민등록번호 모양, 홈 폴더 경로는 저장 전에 가리지만, 모르는 모양의 비밀은 놓칠 수 있습니다. 프로젝트 폴더와 이 저장소에는 아무것도 쓰지 않습니다./p_polish carry now 다음 세션에서 할 일 이 설치된 handoff 스킬(Matt Pocock, MIT)을 이 세션의 한 턴으로 실행하고, 스킬이 쓴 문서를 같은 방식으로 가려서 보관합니다. 이 세션의 토큰을 씁니다. 스킬이 없으면 설치 명령만 안내하고 직접 만들어 주지 않습니다.--resume 한 세션에는 묻지 않습니다. 질문을 띄울 수 없으면 carry use 로 다음 프롬프트에 붙이고, carry skip 으로 넘깁니다.Pick up an earlier session(밴드에서는 Earlier sessions 버튼)을 열면 이 프로젝트의 최근 24시간 세션이 나오고, 없으면 Up to 7 days로 일주일까지 넓힐 수 있습니다. 각 줄에는 제목과 함께 시간, 바꾼 파일 수, 마지막 프롬프트 일부가 나옵니다. 세션을 누르면 펼쳐져 마지막 프롬프트 전체가 보이고, Hand over to this session을 눌러야 지금 세션에 넘어갑니다. 넘기고 나면 카드에 ✓ Handed over … 줄이 남아 확인할 수 있고, 새 세션에서는 사라집니다. 폴리시 결과를 확인하는 중에는 이 카드가 숨겨집니다. 넘긴 내용은 모델이 다음 프롬프트와 함께 읽는 숨은 메모로 대화에 들어가며, 모델 호출은 일어나지 않습니다. 목록은 Claude Code가 이 컴퓨터에 보관한 세션 파일에서 읽기 때문에, TRAIL을 켜지 않았던 세션도 나옵니다. 목록을 열 때만 각 파일의 앞부분과 끝부분을 읽고, 프롬프트 몇 개와 파일 이름만 가려서 뽑으며, 저장하지는 않습니다. 인계 문서가 있는 세션은 Notes와 Handoff document 중 고릅니다. 명령어로는 /p_polish carry sessions [week]로 목록을 보고 /p_polish carry take <번호> [handoff]로 넘깁니다./p_polish carry setup 이 무료 도구(handoff, session-report, planning-with-files)의 설치 여부와 설치 명령을 보여 줍니다. planning-with-files 가 설치돼 있으면 세션 흔적은 제안하지 않습니다./p_polish carry clear 는 이 프로젝트의 것을, carry clear all 은 모든 프로젝트의 것을 지웁니다./p_polish 와 /polish 는 같은 명령입니다.
| 입력 | 동작 |
|---|---|
/p_polish | 창을 엽니다. 데스크톱 앱에서 띠를 줄여 두었다면 다시 펼칩니다. |
/p_polish <프롬프트> | 입력한 프롬프트를 재작성해서 창에 표시합니다. |
/p_polish auto | AUTO 를 켜거나 끕니다. |
/p_polish target | Session Model 의 현재 값과 선택 가능한 이름을 출력합니다. |
/p_polish target <이름> | Session Model 을 변경합니다. auto, opus-5.5, sonnet-5.5, gpt-6-astra, gpt-5.6 중 하나입니다. |
/p_polish model | Polish Model 의 현재 값과 목록을 출력합니다. |
/p_polish model <이름> | Polish Model 을 변경합니다. 목록에 없는 모델 이름도 입력할 수 있습니다. |
/p_polish effort <단계> | effort 를 변경합니다. low, medium, high, xhigh, max 중 하나입니다. |
/p_polish usage | 재작성 호출이 쓴 토큰(입력, 캐시 쓰기, 캐시 읽기, 출력)과 캐시가 처리한 비율, 재시도 비율, 호출 사이의 간격을 보여 줍니다. 숫자만 기록하고 글은 저장하지 않으며, /p_polish usage clear 로 지웁니다. 기록이 10회 쌓이면, 다시 읽히지 않는 캐시 표시는 이 숫자를 보고 스스로 끄고 지금 켜진 표시도 함께 보여 줍니다. |
| /p_polish carry | 세션 이어가기. on, off, now [할 일], setup, sessions [week], take <번호> [handoff], show [handoff], use [trail\|handoff], skip, clear [all]
hooks/register.tsx 245 lines1// The mod's entry: it hands each event to core.ts, which holds the pane's
2// logic, and draws the pane with the frontend of the surface that asks, off
3// the same View. The Claude desktop app has desktop.tsx; every other surface,
4// the terminal and those that draw from a grid of cells like it (the VS Code
5// extension, the mobile app), has terminal.tsx.
6//
7// A surface module is named here, by `module`, because the engine reads the
8// paths of the modules from this file: a frontend is handed the elements.
9import type { EngineInterface, Register } from 'claude-code'
10
11import {
12 actsOf,
13 bandOf,
14 onClose,
15 onCommand,
16 onFault,
17 onStart,
18 onSubmit,
19 viewOf,
20} from './core'
21import {
22 onCarried,
23 onCarryOver,
24 onMeasure,
25 onSent,
26 onSkill,
27 onTurnEnd,
28} from './carry'
29import { bandChip, desktopBand } from './band'
30import { desktopPane, onControl } from './desktop'
31import { terminalPane } from './terminal'
32import type { Layout, Marks } from './view'
33
34// The pane's id, written out in this file as well as in core.ts: the matchers
35// below are read from here, and `claude plugin validate` reads a literal.
36const PANE = 'prompt-polish'
37
38/**
39 * The surface modules the pane or the band may draw, where the surface runs
40 * them: the terminal and the desktop do. The other surfaces hold the element
41 * in their tables too, and draw an empty box for it.
42 */
43function marksOf(
44 surface: string,
45 table: ReturnType<EngineInterface['ui']['resolve']>,
46): Marks {
47 if (!(surface === 'terminal' || surface === 'desktop') || !('Client' in table)) {
48 return {}
49 }
50
51 return {
52 pulse: (phase, color) => (
53 <table.Client
54 key="pulse"
55 module="./pulse.tsx"
56 props={{ kind: phase, color }}
57 />
58 ),
59 spinner: (since, now, color) => (
60 <table.Client
61 key="spinner"
62 module="./spinner.tsx"
63 props={{ since, now, color }}
64 />
65 ),
66 ...(surface === 'terminal'
67 ? {
68 bar: (width: number, color: string, dim: string) => (
69 <table.Client
70 key="bar"
71 module="./bar.tsx"
72 width={width}
73 height={1}
74 props={{ width, color, dim }}
75 />
76 ),
77 }
78 : {
79 catcher: (key: string, rows: number) => (
80 <table.Box position="absolute" top={0} bottom={0} left={0} right={0}>
81 <table.Client
82 key={`hit-${key}`}
83 module="./hit.tsx"
84 props={{ press: key, rows }}
85 width="100%"
86 height="100%"
87 />
88 </table.Box>
89 ),
90 }),
91 }
92}
93
94export const register: Register = (on, options) => {
95 on('session.start', async ($, e, next) => {
96 await onStart($, options)
97
98 return next(e)
99 })
100
101 // The command answers itself: core.ts says what, and this is the answer.
102 on('command.run', { command: ['polish', 'p_polish'] }, async ($, e) => {
103 try {
104 return { text: (await onCommand($, e.args, options)).text }
105 } catch (error) {
106 // A store or a file that cannot be written is told, not left as no answer.
107 return { text: `Prompt Polish could not do that: ${String(error).slice(0, 200)}` }
108 }
109 })
110
111 // A prompt goes on as written, as polished, or not at all: its text is what
112 // the hook answers `next` with. A hook that fails lets it go as written.
113 on('prompt.submit', async ($, e, next) => {
114 // The first prompt of a session: asked whether to pick up where the last
115 // one stopped, before the polish, which is about this prompt alone.
116 const carry = await onCarryOver($, e).catch(() => undefined)
117 const answer = await onSubmit($, e, options)
118
119 if (answer !== undefined && 'drop' in answer) {
120 return answer
121 }
122
123 const sent = answer === undefined ? e : { ...e, text: answer.text }
124
125 // The earlier trail is spent before this prompt is kept in the new one.
126 const notes = await onCarried($, carry).catch(() => [])
127
128 // The trail is the person's own, and off until they turn it on; a failure
129 // to keep it never holds the prompt.
130 await onSent($, sent).catch(() => undefined)
131
132 return next(
133 notes.length === 0
134 ? sent
135 : { ...sent, context: [...(sent.context ?? []), ...notes] },
136 )
137 }).catch(($, e, next) => next(e))
138
139 // The handoff skill's prompt was expanded: the turn that follows is its.
140 on('skill.prompt', async ($, e, next) => {
141 await onSkill($, e.skill)
142
143 return next(e)
144 })
145
146 // The context passed the threshold: a handoff document is offered, never
147 // written unasked. The asking is detached from this hook.
148 on('session.measure', async ($, e, next) => {
149 await onMeasure($, e.context.percent, e.changed)
150
151 return next(e)
152 })
153
154 // A turn of the main conversation ended: the trail, if on, takes what it
155 // did. The work goes on after the hook, which only observes.
156 on('turn.complete', ($, e, next) => {
157 if (e.agentId === undefined) {
158 void onTurnEnd($, e.answer, e.isAborted).catch(() => undefined)
159 }
160
161 return next(e)
162 })
163
164 // The person closing the pane over a preview is "keep my draft".
165 on('ui.close', { id: PANE }, async ($, e, next) => {
166 await onClose($, e.origin, options)
167
168 return next(e)
169 })
170
171 // A catcher that failed would lie dead over its control. The engine draws
172 // the pane again after a fault: without catchers, on its buttons alone.
173 on('ui.fault', async ($, e, next) => {
174 await onFault($, e.module)
175
176 return next(e)
177 })
178
179 // A click a catcher took over one of the desktop's controls, posted by key.
180 on('ui.message', async ($, e, next) => {
181 await onControl($, e, options)
182
183 return next(e)
184 })
185
186 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
187 const table = $.ui.resolve(e)
188 const view = await viewOf($, options)
189 const layout: Layout = {
190 columns: e.props.bodyColumns,
191 isDocked: e.props.placement === 'dock',
192 bodyRows: e.props.scroll.bodyRows,
193 isFullscreen: e.viewport?.isFullscreen === true,
194 }
195 const marks = marksOf(e.surface, table)
196 const act = actsOf($, options)
197
198 return e.surface === 'desktop'
199 ? desktopPane(table, view, act, layout, marks)
200 : terminalPane(table, view, act, layout, marks)
201 })
202
203 // The band right above the prompt box is every mod's: the desktop draws it
204 // there when the person's option says so, and what the others draw stays.
205 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
206 if (e.surface !== 'desktop' || (await bandOf($, options)) !== 'open') {
207 return next(e)
208 }
209
210 const table = $.ui.resolve(e)
211 const view = await viewOf($, options)
212 const layout: Layout = {
213 columns: e.props.bodyColumns,
214 isDocked: false,
215 bodyRows: e.props.scroll.bodyRows,
216 isFullscreen: false,
217 }
218 const theirs = await next(e)
219
220 return desktopBand(
221 table,
222 view,
223 actsOf($, options),
224 layout,
225 marksOf(e.surface, table),
226 theirs,
227 )
228 })
229
230 // Minimized, the band is not drawn above the prompt box: a chip in the
231 // prompt's footer, among the labels the engine draws there, opens it again.
232 on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
233 if (e.surface !== 'desktop' || (await bandOf($, options)) !== 'minimized') {
234 return next(e)
235 }
236
237 return bandChip(
238 $.ui.resolve(e),
239 await viewOf($, options),
240 actsOf($, options),
241 e.props.modes,
242 )
243 })
244}
245hooks/core.ts 1356 lines1// The pane's one body of logic, whatever surface draws it: the state it keeps,
2// what each control does, and the polish itself. The surfaces differ only in
3// how they draw it (terminal.tsx, desktop.tsx), so everything they share is
4// here and what they are given is a View (view.ts) and an Act.
5import { atom, read, update } from 'claude-code'
6import type {
7 EngineInterface,
8 ModelCompleteRequest,
9 ModelCompleteResult,
10 ModelEffort,
11 PluginOptions,
12 PromptSubmitInput,
13} from 'claude-code'
14
15import type { Held, LogKind, LogLine, Menu, Target, TargetChoice } from '../types'
16import { CHOICES, GUIDES, isChoice, targetOf } from './guides'
17import { cachePlanOf, emptyLedger, isLedger, recorded, reportOf } from './ledger'
18import type { CachePlan } from './ledger'
19import {
20 ANSWERS,
21 easyOf,
22 EFFORTS,
23 isEffort,
24 isPolishable,
25 modelsOf,
26 polishedOf,
27 questionOf,
28 requestOf,
29 rowsOf,
30} from './polish'
31import type { Polished } from './polish'
32import {
33 answerOf,
34 filesOf,
35 mentionedIn,
36 pathsOf,
37 projectOf,
38 SKIPPED_DIRS,
39} from './project'
40import type { Read } from './project'
41import {
42 carryStart,
43 onCarry,
44 openSessions,
45 pickSession,
46 sessionsView,
47 setKind,
48 setRange,
49 takeSession,
50 toggleSessions,
51 toggleTrail,
52} from './carry'
53import type { Act, View } from './view'
54
55// Also written out in register.tsx, where the matchers on it are read from.
56export const PANE = 'prompt-polish'
57export const TITLE = 'Prompt Polish'
58const PANE_COLUMNS = 71
59export const IDLE_ROWS = 9
60const HINT_MS = 5000
61// How many polishes of one draft are kept to page through.
62const VERSIONS = 10
63
64const GPT_TARGETS: readonly Target[] = ['gpt-6-astra', 'gpt-5.6']
65
66const isAuto = atom({ plugin: 'prompt-polish', key: 'isAuto' } as const, true)
67const target = atom({ plugin: 'prompt-polish', key: 'target' } as const, 'auto')
68const isBusy = atom({ plugin: 'prompt-polish', key: 'isBusy' } as const, false)
69const busySince = atom(
70 { plugin: 'prompt-polish', key: 'busySince' } as const,
71 null,
72)
73const menu = atom({ plugin: 'prompt-polish', key: 'menu' } as const, null)
74const original = atom(
75 { plugin: 'prompt-polish', key: 'original' } as const,
76 null,
77)
78const proposal = atom(
79 { plugin: 'prompt-polish', key: 'proposal' } as const,
80 null,
81)
82const versions = atom({ plugin: 'prompt-polish', key: 'versions' } as const, [])
83const version = atom({ plugin: 'prompt-polish', key: 'version' } as const, 0)
84const held = atom({ plugin: 'prompt-polish', key: 'held' } as const, null)
85const isReviewed = atom(
86 { plugin: 'prompt-polish', key: 'isReviewed' } as const,
87 false,
88)
89const isAnswering = atom(
90 { plugin: 'prompt-polish', key: 'isAnswering' } as const,
91 false,
92)
93const log = atom({ plugin: 'prompt-polish', key: 'log' } as const, [])
94const isLogOpen = atom(
95 { plugin: 'prompt-polish', key: 'isLogOpen' } as const,
96 false,
97)
98const isKeysOpen = atom(
99 { plugin: 'prompt-polish', key: 'isKeysOpen' } as const,
100 false,
101)
102const isGuideOpen = atom(
103 { plugin: 'prompt-polish', key: 'isGuideOpen' } as const,
104 false,
105)
106const hintUntil = atom(
107 { plugin: 'prompt-polish', key: 'hintUntil' } as const,
108 null,
109)
110const isPlain = atom({ plugin: 'prompt-polish', key: 'isPlain' } as const, false)
111const isSetupOpen = atom(
112 { plugin: 'prompt-polish', key: 'isSetupOpen' } as const,
113 false,
114)
115const isOriginalOpen = atom(
116 { plugin: 'prompt-polish', key: 'isOriginalOpen' } as const,
117 false,
118)
119// Written in carry.ts too: the scan that lists the state reads each atom
120// from the file that reads it.
121const isTrailing = atom(
122 { plugin: 'prompt-polish', key: 'isTrailing' } as const,
123 false,
124)
125const isBandOpen = atom(
126 { plugin: 'prompt-polish', key: 'isBandOpen' } as const,
127 true,
128)
129const models = atom({ plugin: 'prompt-polish', key: 'models' } as const, [])
130const model = atom({ plugin: 'prompt-polish', key: 'model' } as const, null)
131const effort = atom({ plugin: 'prompt-polish', key: 'effort' } as const, null)
132
133// The polish a button press started, for the Cancel press that follows it.
134let stop: AbortController | null = null
135
136type Proposed = { isProposed: boolean; isStopped?: boolean; note: string }
137
138async function resolveTarget($: EngineInterface): Promise<Target> {
139 const choice = await read($, target)
140
141 return choice === 'auto' ? targetOf(await $.session.model()) : choice
142}
143
144/** How a choice of the model the prompt is for reads: its guide's name, or what "auto" came to. */
145const choiceLabel = (choice: TargetChoice, resolved: Target): string =>
146 choice === 'auto'
147 ? `${GUIDES[resolved].label} (Detected)`
148 : GUIDES[choice].label
149
150/** The model and effort that polish: the pane's picks over the mod's options. */
151async function pickedOf(
152 $: EngineInterface,
153 options: PluginOptions,
154): Promise<{ polishModel: string; effort: ModelEffort }> {
155 const level = (await read($, effort)) ?? options.effort
156
157 return {
158 polishModel: (await read($, model)) ?? String(options.polishModel ?? 'sonnet'),
159 effort: isEffort(level) ? level : 'low',
160 }
161}
162
163async function loadModels($: EngineInterface): Promise<void> {
164 const rows = await $.config.list().catch(() => [])
165 const listed = rows.find(row => row.key === 'model')?.options ?? []
166 const list = modelsOf(listed, await $.session.model())
167 await update($, models, () => list)
168}
169
170async function toggleLog($: EngineInterface): Promise<void> {
171 await update($, isLogOpen, isOpen => !isOpen)
172}
173
174async function toggleKeys($: EngineInterface): Promise<void> {
175 await update($, isKeysOpen, isOpen => !isOpen)
176}
177
178/** Opens the pane to read the polish on show in full, or to rest. */
179async function showPanel(
180 $: EngineInterface,
181 isLogged = false,
182): Promise<void> {
183 const text = await read($, proposal)
184 const draft = await read($, original)
185
186 if (isLogged) {
187 await update($, isLogOpen, () => true)
188 }
189
190 await openPane(
191 $,
192 text !== null && draft !== null ? rowsOf(draft, text) : IDLE_ROWS,
193 false,
194 )
195}
196
197/** The band's Sessions button: the pane opens beside the conversation, with the list of earlier sessions open. */
198async function openSessionsPanel($: EngineInterface): Promise<void> {
199 await openSessions($)
200 await showPanel($)
201}
202
203async function toggleSetup($: EngineInterface): Promise<void> {
204 await update($, isSetupOpen, isOpen => !isOpen)
205}
206
207async function toggleOriginal($: EngineInterface): Promise<void> {
208 const isOpen = !(await read($, isOriginalOpen))
209 await update($, isOriginalOpen, () => isOpen)
210 await $.store.set('isOriginalOpen', isOpen)
211}
212
213async function toggleGuide($: EngineInterface): Promise<void> {
214 await update($, isGuideOpen, isOpen => !isOpen)
215}
216
217async function toggleMenu($: EngineInterface, which: Menu): Promise<void> {
218 await update($, menu, shown => (shown === which ? null : which))
219}
220
221async function closeMenu($: EngineInterface): Promise<void> {
222 await update($, menu, () => null)
223}
224
225async function pickTarget($: EngineInterface, value: string): Promise<void> {
226 if (!isChoice(value)) {
227 return
228 }
229
230 await update($, menu, () => null)
231 await update($, target, () => value)
232 await $.store.set('target', value)
233}
234
235async function pickModel($: EngineInterface, value: string): Promise<void> {
236 await update($, model, () => value)
237 await $.store.set('model', value)
238}
239
240async function pickEffort($: EngineInterface, value: string): Promise<void> {
241 if (!isEffort(value)) {
242 return
243 }
244
245 await update($, effort, () => value)
246 await $.store.set('effort', value)
247}
248
249async function say(
250 $: EngineInterface,
251 kind: LogKind,
252 text: string,
253): Promise<void> {
254 const line: LogLine = { at: await $.clock.now(), kind, text }
255 await update($, log, lines => [...lines, line].slice(-30))
256}
257
258/**
259 * Opens the pane, or resizes the open one: `columns` docked beside a
260 * fullscreen transcript, `rows` inline above the prompt. `isAsking` asks for
261 * the keyboard, which the surface gives over an empty prompt box.
262 */
263function openPane($: EngineInterface, rows: number, isAsking: boolean) {
264 return $.ui.open({
265 id: PANE,
266 title: TITLE,
267 columns: PANE_COLUMNS,
268 rows,
269 ...(isAsking ? ({ focus: true } as const) : {}),
270 })
271}
272
273/**
274 * Whether the pane is drawn as a band above the prompt box: the Claude desktop
275 * app does when the person's option says so. The terminal and the other
276 * surfaces always have the pane. The band is there open or minimized (`bandOf`).
277 */
278export async function isBandOn(
279 $: EngineInterface,
280 options: PluginOptions,
281): Promise<boolean> {
282 const surfaces: readonly string[] = await $.session.surfaces().catch(() => [])
283
284 return options.placement === 'band' && surfaces.includes('desktop')
285}
286
287/**
288 * Where the band stands: `off` where it is not drawn, `open` as the band above
289 * the prompt box, `minimized` as a chip in the prompt's footer (the band is
290 * then not drawn at all, so nothing frames an icon above the prompt box).
291 */
292export async function bandOf(
293 $: EngineInterface,
294 options: PluginOptions,
295): Promise<'off' | 'open' | 'minimized'> {
296 if (!(await isBandOn($, options))) {
297 return 'off'
298 }
299
300 return (await read($, isBandOpen)) ? 'open' : 'minimized'
301}
302
303/** Opens the band, or minimizes it; the next session starts as this one was left. */
304async function setBand($: EngineInterface, isOpen: boolean): Promise<void> {
305 await update($, isBandOpen, () => isOpen)
306 await $.store.set('isBandOpen', isOpen)
307}
308
309/** Whether the pane is to be opened: it is not when the desktop is the one surface, and shows the band. */
310async function needsPane(
311 $: EngineInterface,
312 options: PluginOptions,
313): Promise<boolean> {
314 const surfaces: readonly string[] = await $.session.surfaces().catch(() => [])
315
316 return !(
317 options.placement === 'band' &&
318 surfaces.length > 0 &&
319 surfaces.every(surface => surface === 'desktop')
320 )
321}
322
323// Nothing hands a pane's keyboard back but its close: closed and opened
324// again, the pane stays up and the prompt box has the keys for Enter.
325async function rest(
326 $: EngineInterface,
327 options: PluginOptions,
328): Promise<void> {
329 // The band is where the desktop lives; the pane was opened to read a
330 // polish in full, and is put away when the answer is given.
331 if (!(await needsPane($, options))) {
332 await $.ui.close({ id: PANE }).catch(() => undefined)
333
334 return
335 }
336
337 await $.ui.close({ id: PANE })
338 await openPane($, IDLE_ROWS, false)
339}
340
341const WALK_DEPTH = 3
342const WALK_FILES = 2_000
343
344/** The project's files by walking it, where git cannot list them. */
345async function walk($: EngineInterface, root: string): Promise<string[]> {
346 const found: string[] = []
347 const visit = async (dir: string, depth: number): Promise<void> => {
348 const entries = await $.fs.list(dir === '' ? root : `${root}/${dir}`).catch(() => [])
349
350 for (const entry of entries) {
351 const path = dir === '' ? entry.name : `${dir}/${entry.name}`
352
353 if (found.length >= WALK_FILES) {
354 return
355 }
356
357 if (entry.kind === 'file') {
358 found.push(path)
359 } else if (
360 entry.kind === 'dir' &&
361 depth < WALK_DEPTH &&
362 !SKIPPED_DIRS.includes(entry.name)
363 ) {
364 await visit(path, depth + 1)
365 }
366 }
367 }
368
369 await visit('', 0)
370
371 return found
372}
373
374async function listed($: EngineInterface, root: string): Promise<string[]> {
375 // What git tracks, and what it neither tracks nor ignores; a name outside
376 // ASCII as it is written, not escaped.
377 const git = await $.process
378 .run(
379 [
380 'git',
381 '-c',
382 'core.quotepath=false',
383 'ls-files',
384 '--cached',
385 '--others',
386 '--exclude-standard',
387 ],
388 { cwd: root, timeoutMs: 10_000 },
389 )
390 .catch(() => undefined)
391
392 return git !== undefined && git.exitCode === 0 && git.stdout.trim() !== ''
393 ? pathsOf(git.stdout)
394 : pathsOf((await walk($, root)).join('\n'))
395}
396
397function readerOf($: EngineInterface, root: string): Read {
398 return async path => {
399 const text = await $.fs.read(`${root}/${path}`).catch(() => undefined)
400
401 // A NUL says the file is not text, whatever its name.
402 return text === undefined || text.includes('\0') ? undefined : text
403 }
404}
405
406/** The start of each file `draft` names, then of those `answer` names, among `paths`. */
407const namedOf = (
408 paths: readonly string[],
409 draft: string,
410 answer: string,
411 read: Read,
412): Promise<string> =>
413 filesOf(
414 [...new Set([...mentionedIn(draft, paths), ...mentionedIn(answer, paths)])],
415 read,
416 )
417
418/**
419 * Reads what one polish is given besides the draft: the project as it stands
420 * on disk, the files the draft and the last answer name, and that answer.
421 * Nothing here calls a model.
422 */
423async function gather($: EngineInterface, draft: string): Promise<Held> {
424 const answer = answerOf(await $.session.messages().catch(() => []))
425 const root = await $.session.root().catch(() => undefined)
426
427 if (root === undefined) {
428 return { project: '', files: '', answer }
429 }
430
431 const paths = await listed($, root)
432 const read = readerOf($, root)
433
434 return {
435 project: await projectOf(paths, read),
436 files: await namedOf(paths, draft, answer, read),
437 answer,
438 }
439}
440
441/**
442 * What a retry of an edited draft is given: the project and the answer as
443 * its polish read them, and the files the draft now names.
444 */
445async function regather(
446 $: EngineInterface,
447 kept: Held,
448 draft: string,
449): Promise<Held> {
450 const root = await $.session.root().catch(() => undefined)
451
452 if (root === undefined) {
453 return kept
454 }
455
456 const paths = await listed($, root)
457
458 return {
459 ...kept,
460 files: await namedOf(paths, draft, kept.answer, readerOf($, root)),
461 }
462}
463
464async function polish(
465 $: EngineInterface,
466 draft: string,
467 guide: Target,
468 given: Held,
469 options: PluginOptions,
470 signal: AbortSignal,
471 rejected?: string,
472): Promise<Polished> {
473 const request = requestOf(
474 { draft, target: guide, held: given, rejected, plan: await planOf($) },
475 { ...options, ...(await pickedOf($, options)) },
476 )
477
478 const reply = await $.model.complete(request, { signal })
479 await spend($, request, reply, given, draft, rejected !== undefined)
480
481 return polishedOf(reply)
482}
483
484/** Where the cache marks go, by what this person's earlier calls cost: see ledger.ts. */
485async function planOf($: EngineInterface): Promise<CachePlan> {
486 try {
487 const stored = await $.store.get('usage')
488
489 return cachePlanOf(isLedger(stored) ? stored : emptyLedger(0))
490 } catch {
491 return { system: true, project: true, turn: true }
492 }
493}
494
495/**
496 * Notes what a polish call cost, in numbers: see ledger.ts. A call that was
497 * cut before it was answered cost nothing worth counting, and a ledger that
498 * cannot be kept is no reason to fail a polish.
499 */
500async function spend(
501 $: EngineInterface,
502 request: ModelCompleteRequest,
503 reply: ModelCompleteResult,
504 given: Held,
505 draft: string,
506 isRetry: boolean,
507): Promise<void> {
508 if (!reply.isAnswered && reply.reason === 'aborted') {
509 return
510 }
511
512 try {
513 const now = await $.clock.now()
514 const stored = await $.store.get('usage')
515 const system =
516 typeof request.system === 'string'
517 ? request.system.length
518 : (request.system ?? []).reduce((n, block) => n + block.text.length, 0)
519
520 await $.store.set(
521 'usage',
522 recorded(
523 isLedger(stored) ? stored : emptyLedger(now),
524 {
525 at: now,
526 model: request.model,
527 kind: isRetry ? 'retry' : 'polish',
528 chars: [
529 system,
530 given.project.length,
531 given.files.length + given.answer.length,
532 draft.length,
533 ],
534 },
535 reply.usage,
536 reply.isAnswered,
537 ),
538 )
539 } catch {
540 // The ledger is a measurement; a polish does not depend on it.
541 }
542}
543
544/** What one polish came to; a failure and an unchanged draft are logged by `generate`, a polish by whoever has it. */
545type Composed =
546 | { kind: 'polished'; text: string; guide: Target; given: Held }
547 | { kind: 'stopped' }
548 | { kind: 'failed'; reason: string }
549 | { kind: 'clear' }
550
551/**
552 * Marks a polish as running, for the pane, the band and the status line, and
553 * makes the Stop press its own. Whoever begins one ends it.
554 */
555async function begin(
556 $: EngineInterface,
557 options: PluginOptions,
558): Promise<AbortController> {
559 const mine = new AbortController()
560 stop = mine
561 const startedAt = await $.clock.now()
562 await update($, busySince, () => startedAt)
563 await update($, isBusy, () => true)
564 $.ui.status('Polishing prompt…')
565
566 // The loading mark is the pane's: a polish begun with the pane closed opens
567 // it, unless the band above the prompt box is where it is drawn.
568 if (
569 (await needsPane($, options)) &&
570 !(await $.ui.panes()).some(pane => pane.id === PANE)
571 ) {
572 await openPane($, IDLE_ROWS, false)
573 }
574
575 return mine
576}
577
578async function end($: EngineInterface): Promise<void> {
579 stop = null
580 $.ui.status(undefined)
581 await update($, isBusy, () => false)
582 await update($, busySince, () => null)
583}
584
585/**
586 * One polish of `draft`: what it is given to read, and what the model made of
587 * it. `kept` is what an earlier polish of the draft was given, for a retry of
588 * it; `isEdited` says the draft is not the one it read.
589 *
590 * A polish reads the project and the last answer anew. A retry is given what
591 * its polish read, unchanged, so the request opens as the last one did and
592 * the prompt cache serves that part again; of a draft edited since, the files
593 * it now names are read, and the rest is as it was.
594 */
595async function generate(
596 $: EngineInterface,
597 draft: string,
598 options: PluginOptions,
599 signal: AbortSignal,
600 retry: { rejected?: string; kept: Held | null; isEdited: boolean },
601): Promise<Composed> {
602 const guide = await resolveTarget($)
603 const given =
604 retry.kept === null
605 ? await gather($, draft)
606 : retry.isEdited
607 ? await regather($, retry.kept, draft)
608 : retry.kept
609 await update($, held, () => given)
610 const result = await polish(
611 $,
612 draft,
613 guide,
614 given,
615 options,
616 signal,
617 retry.rejected,
618 )
619
620 // A reply that raced the Cancel press is dropped with it.
621 if (signal.aborted) {
622 return { kind: 'stopped' }
623 }
624
625 if (!result.isPolished) {
626 await say($, 'fail', result.reason)
627
628 return { kind: 'failed', reason: result.reason }
629 }
630
631 if (result.text === draft.trim()) {
632 await say($, 'keep', 'No changes')
633
634 return { kind: 'clear' }
635 }
636
637 return { kind: 'polished', text: result.text, guide, given }
638}
639
640/** What a polish that is no polish says, as the note a button press toasts. */
641function noteOf(made: Exclude<Composed, { kind: 'polished' }>): string {
642 return made.kind === 'stopped'
643 ? 'Polish stopped.'
644 : made.kind === 'failed'
645 ? `Polish failed. ${made.reason}.`
646 : 'Already clear. No changes.'
647}
648
649/** The words a record row gives a polish: for which guide, and how much it grew. */
650const polishedRow = (guide: Target, draft: string, text: string): string =>
651 `${GUIDES[guide].label} · ${draft.trim().length} → ${text.length} chars`
652
653/**
654 * Polishes `draft` and holds the result as the proposal the pane previews;
655 * the prompt box is left as it is. `rejected` is an earlier proposal of the
656 * same draft, to polish away from.
657 */
658async function propose(
659 $: EngineInterface,
660 draft: string,
661 options: PluginOptions,
662 rejected?: string,
663): Promise<Proposed> {
664 if (await read($, isBusy)) {
665 return { isProposed: false, note: 'Already polishing. Please wait.' }
666 }
667
668 if (draft.trim() === '') {
669 return {
670 isProposed: false,
671 note: 'Nothing to polish. Type a prompt first.',
672 }
673 }
674
675 const mine = await begin($, options)
676
677 try {
678 const kept = rejected === undefined ? null : await read($, held)
679 const isEdited = draft.trim() !== (await read($, original))?.trim()
680 const made = await generate($, draft, options, mine.signal, {
681 rejected,
682 kept,
683 isEdited,
684 })
685
686 if (made.kind !== 'polished') {
687 return {
688 isProposed: false,
689 ...(made.kind === 'stopped' ? { isStopped: true } : {}),
690 note: noteOf(made),
691 }
692 }
693
694 const text = made.text
695 // A retry of the same draft adds a version to those made of it, unless it
696 // came to one of them again; a polish, or a retry of a draft edited
697 // since, starts them over.
698 const earlier =
699 rejected === undefined || isEdited ? [] : await read($, versions)
700 const again = earlier.indexOf(text)
701 const paged = (again === -1 ? [...earlier, text] : earlier).slice(-VERSIONS)
702 await update($, original, () => draft)
703 await update($, versions, () => paged)
704 await update($, version, () => (again === -1 ? paged.length - 1 : again))
705 await update($, proposal, () => text)
706 await update($, isReviewed, () => true)
707 await say(
708 $,
709 rejected === undefined ? 'polish' : 'refresh',
710 polishedRow(made.guide, draft, text),
711 )
712
713 // Where the band is, the pane is opened to read the polish in full, and
714 // leaves the keyboard where it is: the band has the answers.
715 const isPaneTheSurface = await needsPane($, options)
716 await openPane($, rowsOf(draft, text), isPaneTheSurface)
717
718 return {
719 isProposed: true,
720 note: `Polished for ${GUIDES[made.guide].label}. Check it, then apply or keep.`,
721 }
722 } finally {
723 await end($)
724 }
725}
726
727async function polishBox(
728 $: EngineInterface,
729 options: PluginOptions,
730): Promise<void> {
731 const box = (await $.prompt.read()).text
732 $.ui.toast((await propose($, box, options)).note)
733}
734
735/** Polishes again, away from the proposal on show: the box's draft, or the one it was made from. */
736async function refresh(
737 $: EngineInterface,
738 options: PluginOptions,
739): Promise<void> {
740 const shown = await read($, proposal)
741 const draft = await read($, original)
742
743 if (shown === null || draft === null) {
744 return
745 }
746
747 const box = (await $.prompt.read()).text
748 const again = box.trim() === '' ? draft : box
749 $.ui.toast((await propose($, again, options, shown)).note)
750}
751
752/** Puts the version before or after the one on preview there in its place. */
753async function step($: EngineInterface, by: -1 | 1): Promise<void> {
754 const at = (await read($, version)) + by
755 const text = (await read($, versions))[at]
756
757 if (text === undefined || (await read($, proposal)) === null) {
758 return
759 }
760
761 await update($, version, () => at)
762 await update($, proposal, () => text)
763}
764
765/** Puts the proposal in the prompt box, keeping what the box held for Undo. */
766async function apply(
767 $: EngineInterface,
768 options: PluginOptions,
769): Promise<void> {
770 const text = await read($, proposal)
771 const draft = await read($, original)
772
773 if (text === null) {
774 return
775 }
776
777 const box = (await $.prompt.read()).text
778 const filled = await $.prompt.fill({ text })
779
780 if (!filled.isFilled) {
781 $.ui.toast('Could not change the prompt box.')
782
783 return
784 }
785
786 const kept = box.trim() === '' ? draft : box
787 await update($, proposal, () => null)
788 await update($, versions, () => [])
789 await update($, held, () => null)
790 await update($, original, () => kept)
791 await say($, 'apply', `${text.length} chars`)
792 await rest($, options)
793 $.ui.toast('Applied. Press Enter to send.')
794}
795
796/** Drops the proposal; a prompt box the held draft left empty gets it back. */
797async function keep($: EngineInterface): Promise<void> {
798 const draft = await read($, original)
799
800 if ((await read($, proposal)) === null) {
801 return
802 }
803
804 if (draft !== null && (await $.prompt.read()).text.trim() === '') {
805 await $.prompt.fill({ text: draft })
806 }
807
808 await update($, proposal, () => null)
809 await update($, versions, () => [])
810 await update($, original, () => null)
811 await say($, 'keep', 'Original kept')
812}
813
814async function discard(
815 $: EngineInterface,
816 options: PluginOptions,
817): Promise<void> {
818 await keep($)
819 await rest($, options)
820}
821
822async function restore($: EngineInterface): Promise<void> {
823 const draft = await read($, original)
824
825 if (draft === null) {
826 return
827 }
828
829 const filled = await $.prompt.fill({ text: draft })
830
831 if (filled.isFilled) {
832 await update($, original, () => null)
833 }
834}
835
836async function settle(
837 $: EngineInterface,
838 options: PluginOptions,
839): Promise<void> {
840 if ((await read($, proposal)) !== null) {
841 await update($, proposal, () => null)
842 await update($, versions, () => [])
843
844 if (!(await needsPane($, options))) {
845 await $.ui.close({ id: PANE }).catch(() => undefined)
846 }
847 }
848
849 if ((await read($, original)) !== null) {
850 await update($, original, () => null)
851 }
852
853 if (await read($, isReviewed)) {
854 await update($, isReviewed, () => false)
855 }
856}
857
858// Takes down the note a switch of AUTO put up, unless a later switch renewed it.
859async function hideHint($: EngineInterface, until: number): Promise<void> {
860 await update($, hintUntil, shown => (shown === until ? null : shown))
861}
862
863/** Switches AUTO, and says for a few seconds what Enter does from now on. */
864async function toggleAuto($: EngineInterface): Promise<void> {
865 const isOn = !(await read($, isAuto))
866 const until = (await $.clock.now()) + HINT_MS
867 await update($, isAuto, () => isOn)
868 await update($, hintUntil, () => until)
869 await $.store.set('isAuto', isOn)
870 $.clock.after(HINT_MS, () => void hideHint($, until))
871}
872
873/** What each control of the pane does, by the name a frontend has for it. */
874export function actsOf($: EngineInterface, options: PluginOptions): Act {
875 return {
876 guide: () => void toggleGuide($),
877 auto: () => void toggleAuto($),
878 trail: () => void toggleTrail($),
879 sessions: () => void toggleSessions($),
880 sessionsPanel: () => void openSessionsPanel($),
881 sessionsRange: range => void setRange($, range),
882 sessionPick: id => void pickSession($, id),
883 sessionKind: kind => void setKind($, kind),
884 sessionTake: () => void takeSession($),
885 menu: which => void toggleMenu($, which),
886 done: () => void closeMenu($),
887 target: value => void pickTarget($, value),
888 model: value => void pickModel($, value),
889 effort: value => void pickEffort($, value),
890 polish: () => void polishBox($, options),
891 apply: () => void apply($, options),
892 retry: () => void refresh($, options),
893 keep: () => void discard($, options),
894 undo: () => void restore($),
895 stop: () => stop?.abort(),
896 step: by => void step($, by),
897 log: () => void toggleLog($),
898 keys: () => void toggleKeys($),
899 setup: () => void toggleSetup($),
900 original: () => void toggleOriginal($),
901 panel: () => void showPanel($),
902 history: () => void showPanel($, true),
903 band: isOpen => void setBand($, isOpen),
904 }
905}
906
907// What Enter does under each setting of AUTO, said alike.
908const HINT_ON = 'AUTO ON · Enter polishes first and asks you before sending.'
909const HINT_OFF = 'AUTO OFF · Enter sends right away, with no polish.'
910
911/** The state as the pane draws it, read once: the same for every surface. */
912export async function viewOf(
913 $: EngineInterface,
914 options: PluginOptions,
915): Promise<View> {
916 const choice = await read($, target)
917 const resolved = await resolveTarget($)
918 // What "auto" comes to, whichever model is picked: its row in the list
919 // names the session's model, not the pick.
920 const detected =
921 choice === 'auto' ? resolved : targetOf(await $.session.model())
922 const picked = await pickedOf($, options)
923 const preview = await read($, proposal)
924 const isRunning = await read($, isBusy)
925 const isWaiting = await read($, isAnswering)
926 const isOn = await read($, isAuto)
927 const now = await $.clock.now()
928 const hintAt = await read($, hintUntil)
929
930 return {
931 phase:
932 isRunning ? 'busy' : preview !== null || isWaiting ? 'review' : 'idle',
933 isOn,
934 isTrailing: await read($, isTrailing),
935 sessions: await sessionsView($),
936 isRunning,
937 isAnswering: isWaiting,
938 isGpt: GPT_TARGETS.includes(resolved),
939 guide: GUIDES[resolved].label,
940 about: GUIDES[resolved].about,
941 isGuideShown: await read($, isGuideOpen),
942 choice,
943 targetLabel: choiceLabel(choice, resolved),
944 targets: CHOICES.map(value => ({
945 value,
946 label: choiceLabel(value, detected),
947 })),
948 models: [
949 picked.polishModel,
950 ...(await read($, models)).filter(name => name !== picked.polishModel),
951 ],
952 model: picked.polishModel,
953 effort: picked.effort,
954 menu: await read($, menu),
955 draft: await read($, original),
956 preview,
957 version: await read($, version),
958 versions: (await read($, versions)).length,
959 lines: await read($, log),
960 isLogShown: await read($, isLogOpen),
961 isKeysShown: await read($, isKeysOpen),
962 isSetupShown: await read($, isSetupOpen),
963 isOriginalShown: await read($, isOriginalOpen),
964 hint: hintAt === null ? null : isOn ? HINT_ON : HINT_OFF,
965 since: (await read($, busySince)) ?? now,
966 now,
967 isPlain: await read($, isPlain),
968 }
969}
970
971/** Once, before the first prompt: what the person left set, the commands, the pane. */
972export async function onStart(
973 $: EngineInterface,
974 options: PluginOptions,
975): Promise<void> {
976 const savedAuto = await $.store.get('isAuto')
977 const savedTarget = await $.store.get('target')
978
979 if (typeof savedAuto === 'boolean') {
980 await update($, isAuto, () => savedAuto)
981 }
982
983 if (isChoice(savedTarget)) {
984 await update($, target, () => savedTarget)
985 }
986
987 const savedModel = await $.store.get('model')
988 const savedEffort = await $.store.get('effort')
989
990 if (typeof savedModel === 'string' && savedModel !== '') {
991 await update($, model, () => savedModel)
992 }
993
994 if (isEffort(savedEffort)) {
995 await update($, effort, () => savedEffort)
996 }
997
998 const savedOriginal = await $.store.get('isOriginalOpen')
999
1000 if (typeof savedOriginal === 'boolean') {
1001 await update($, isOriginalOpen, () => savedOriginal)
1002 }
1003
1004 const savedPlain = await $.store.get('isPlain')
1005
1006 if (typeof savedPlain === 'boolean') {
1007 await update($, isPlain, () => savedPlain)
1008 }
1009
1010 const savedBand = await $.store.get('isBandOpen')
1011
1012 if (typeof savedBand === 'boolean') {
1013 await update($, isBandOpen, () => savedBand)
1014 }
1015
1016 await update($, isSetupOpen, () => false)
1017 await carryStart($)
1018
1019 await loadModels($)
1020
1021 // A reload mid-polish drops the call and would leave the pane busy.
1022 await update($, isBusy, () => false)
1023 await update($, isAnswering, () => false)
1024 await update($, busySince, () => null)
1025 await update($, menu, () => null)
1026 await update($, hintUntil, () => null)
1027 // Rows a session kept from an earlier build read as today's do.
1028 await update($, log, lines =>
1029 lines.map(line => ({ ...line, text: easyOf(line.text) })),
1030 )
1031 // One command under two names: `/polish`, and `/p_polish` beside it.
1032 for (const name of ['polish', 'p_polish']) {
1033 await $.command.register({
1034 name,
1035 description:
1036 'Prompt Polish: open the pane, polish a prompt, or change settings',
1037 argumentHint:
1038 '[prompt | auto | target <name> | model <name> | effort <level> | usage | carry | plain | close]',
1039 })
1040 }
1041
1042 if (options.openOnStart !== false && (await needsPane($, options))) {
1043 void openPane($, IDLE_ROWS, false).catch(() => undefined)
1044 }
1045}
1046
1047/** `/polish` and `/p_polish`: the text the command answers with. */
1048export async function onCommand(
1049 $: EngineInterface,
1050 args: string,
1051 options: PluginOptions,
1052): Promise<{ text: string }> {
1053 const word = args.trim()
1054
1055 if (word === 'auto') {
1056 await toggleAuto($)
1057
1058 return {
1059 text: `AUTO: ${(await read($, isAuto)) ? 'ON' : 'OFF'}`,
1060 }
1061 }
1062
1063 if (word === 'target' || word.startsWith('target ')) {
1064 const name = word.slice(6).trim()
1065
1066 if (name !== '' && !isChoice(name)) {
1067 return {
1068 text: `"${name}" is not an option.\nOptions: ${CHOICES.join(', ')}`,
1069 }
1070 }
1071
1072 await pickTarget($, name)
1073 const label = choiceLabel(await read($, target), await resolveTarget($))
1074
1075 return {
1076 text:
1077 name === ''
1078 ? `Session Model: ${label}\nOptions: ${CHOICES.join(', ')}`
1079 : `Session Model: ${label}`,
1080 }
1081 }
1082
1083 if (word === 'model' || word.startsWith('model ')) {
1084 const name = word.slice(5).trim()
1085
1086 if (name === '') {
1087 const now = (await pickedOf($, options)).polishModel
1088
1089 return {
1090 text: `Polish Model: ${now}\nOptions: ${(await read($, models)).join(', ')}`,
1091 }
1092 }
1093
1094 await pickModel($, name)
1095
1096 return { text: `Polish Model: ${name}` }
1097 }
1098
1099 if (word === 'effort' || word.startsWith('effort ')) {
1100 const level = word.slice(6).trim()
1101
1102 if (!isEffort(level)) {
1103 const now = (await pickedOf($, options)).effort
1104
1105 return { text: `Effort: ${now}\nOptions: ${EFFORTS.join(', ')}` }
1106 }
1107
1108 await pickEffort($, level)
1109
1110 return { text: `Effort: ${level}` }
1111 }
1112
1113 // The way out, should a surface's catchers ever take clicks and lose them.
1114 if (word === 'plain') {
1115 const isOff = !(await read($, isPlain))
1116 await update($, isPlain, () => isOff)
1117 await $.store.set('isPlain', isOff)
1118
1119 return {
1120 text: isOff
1121 ? 'Plain buttons: ON. A control is clicked on its words alone.'
1122 : 'Plain buttons: OFF. A control is clicked anywhere on it.',
1123 }
1124 }
1125
1126 if (word === 'usage' || word === 'usage clear') {
1127 if (word === 'usage clear') {
1128 await $.store.delete('usage')
1129
1130 return { text: 'Usage record cleared.' }
1131 }
1132
1133 const stored = await $.store.get('usage')
1134
1135 return { text: reportOf(isLedger(stored) ? stored : emptyLedger(0)) }
1136 }
1137
1138 if (word === 'carry' || word.startsWith('carry ')) {
1139 return { text: await onCarry($, word.slice(5).trim()) }
1140 }
1141
1142 if (word === 'close') {
1143 // Only the desktop's band is minimized, and kept so for the next session:
1144 // a terminal's `close` is the pane's alone.
1145 if (await isBandOn($, options)) {
1146 await setBand($, false)
1147 }
1148
1149 await $.ui.close({ id: PANE }).catch(() => undefined)
1150
1151 return {
1152 text: (await needsPane($, options))
1153 ? 'Prompt Polish closed.'
1154 : 'Prompt Polish minimized. Press its button in the prompt footer to open it.',
1155 }
1156 }
1157
1158 const draft = word === '' ? (await $.prompt.read()).text : args
1159
1160 if (draft.trim() === '') {
1161 if (await isBandOn($, options)) {
1162 await setBand($, true)
1163 }
1164
1165 if (!(await needsPane($, options))) {
1166 return { text: 'Prompt Polish opened.' }
1167 }
1168
1169 const opened = await openPane($, IDLE_ROWS, false)
1170
1171 if (!opened.isPlaced) {
1172 return { text: `Prompt Polish is not shown yet. ${opened.reason}` }
1173 }
1174
1175 // The chord is a terminal's; on any other surface the pane is clicked.
1176 const surfaces: readonly string[] = await $.session
1177 .surfaces()
1178 .catch(() => [])
1179
1180 return {
1181 text: surfaces.includes('terminal')
1182 ? 'Prompt Polish opened. Press ctrl+x tab to use its keys.'
1183 : 'Prompt Polish opened.',
1184 }
1185 }
1186
1187 return { text: (await propose($, draft, options)).note }
1188}
1189
1190/** What a prompt becomes at the hook: stopped, with the reason; its text as it goes on; or as it was. */
1191export type Submitted = { drop: string } | { text: string } | undefined
1192
1193/**
1194 * A prompt submitted from the box. In auto mode it is polished first and the
1195 * person is asked before it goes: the hook holds the prompt while it works and
1196 * while it asks, and then lets it on, as it was written or as polished.
1197 *
1198 * The engine takes a prompt from the box only to run it or to stop it, and a
1199 * stopped one is a row of its own in the conversation ("Prompt blocked by a
1200 * hook") however it is worded. So nothing here stops a prompt that is to go:hooks/carry.ts 819 lines1// Carrying a session over to the next: the session trail the person turns on,
2// the handoff document an installed skill writes on request, the question at
3// the first prompt of a new session about which to pick up, and the offer when
4// a session's context runs full. Everything here is the person's choice: the
5// trail starts off, a document is written only when asked for, nothing is
6// attached to a prompt without a yes, and nothing is sent anywhere.
7import { atom, read, update } from 'claude-code'
8import type { EngineInterface, PromptSubmitInput } from 'claude-code'
9
10import type { SessionRow, SessionsState } from '../types'
11
12import {
13 authorOf,
14 findHandoff,
15 handoffBlock,
16 handoffOffer,
17 HANDOFF_MISSING,
18 isPlanning,
19 markHandoffOffered,
20 readHandoff,
21 recoverHandoff,
22 saveHandoff,
23 setupText,
24 candidatesOf,
25} from './handoff'
26import type { Handoff } from './handoff'
27import { agoOf, DAY_MS, listSessions, notesOf, WEEK_MS } from './sessions'
28import {
29 blockOf,
30 clearTrails,
31 isTrailOn,
32 markOffered,
33 nameOf,
34 offerOf,
35 readTrails,
36 recordPrompt,
37 recordTurn,
38 renderOf,
39 setTrail,
40 storedTrailOf,
41 summaryOf,
42} from './trail'
43import type { Offer } from './trail'
44import type { SessionsView } from './view'
45
46/** The person's switch for the trail, as the pane draws it (core.ts reads it by the same key). */
47const isTrailing = atom(
48 { plugin: 'prompt-polish', key: 'isTrailing' } as const,
49 false,
50)
51/** What `/polish carry use` armed for the next prompt. */
52const carryArmed = atom(
53 { plugin: 'prompt-polish', key: 'carryArmed' } as const,
54 null,
55)
56/** A handoff skill that was started, and whether it has begun its turn. */
57const handoffRun = atom(
58 { plugin: 'prompt-polish', key: 'handoffRun' } as const,
59 null,
60)
61/** The list of earlier sessions the pane shows, and what was picked in it. */
62const sessions = atom(
63 { plugin: 'prompt-polish', key: 'sessions' } as const,
64 {
65 isOpen: false,
66 range: 'day',
67 rows: null,
68 isLoading: false,
69 picked: null,
70 kind: 'notes',
71 done: [],
72 },
73)
74/** The session the context question was asked in, so it is asked once. */
75const measureAsked = atom(
76 { plugin: 'prompt-polish', key: 'measureAsked' } as const,
77 null,
78)
79
80/** A question left unanswered this fast was never asked: nobody is there to answer one. */
81const UNASKED_MS = 250
82
83/** How long after a command answers the skill it started is run. */
84export const RUN_AFTER_MS = 100
85
86/** The context fill, in percent, at which a handoff is offered. */
87export const THRESHOLD = 70
88
89/** Once, before the first prompt: the switch the person left, and nothing pending. */
90export async function carryStart($: EngineInterface): Promise<void> {
91 const saved = await isTrailOn($)
92
93 await update($, isTrailing, () => saved)
94 await update($, carryArmed, () => null)
95 await update($, handoffRun, () => null)
96 await update($, sessions, s => ({
97 ...s,
98 isOpen: false,
99 rows: null,
100 isLoading: false,
101 picked: null,
102 done: [],
103 }))
104}
105
106/** Turns the session trail on or off for this person: kept for the next session, and drawn now. */
107async function turnTrail($: EngineInterface, isOn: boolean): Promise<void> {
108 await setTrail($, isOn)
109 await update($, isTrailing, () => isOn)
110}
111
112// A toast stays about four seconds: each is one short line.
113const TRAIL_ON_TOAST = 'Session trail on · kept on this computer only.'
114const TRAIL_OFF_TOAST = 'Session trail off · nothing more is recorded.'
115
116/** The pane's TRAIL button. */
117export async function toggleTrail($: EngineInterface): Promise<void> {
118 try {
119 const isOn = !(await read($, isTrailing))
120
121 await turnTrail($, isOn)
122 $.ui.toast(isOn ? TRAIL_ON_TOAST : TRAIL_OFF_TOAST)
123 } catch (error) {
124 $.ui.toast(`The trail setting could not be saved: ${String(error).slice(0, 160)}`)
125 }
126}
127
128const CARRY_ON = [
129 'Session trail: ON.',
130 'From now on Prompt Polish keeps, for each project, on this computer only: your last prompts, the end of the last answer, the files changed, the to-do list and the git state. Keys, tokens, passwords, addresses, phone numbers and your home folder are masked before anything is saved.',
131 "It is kept in this plugin's own store in your Claude folder, never in the project or the repository, and no model is called to write it.",
132 '/p_polish carry show prints it, carry clear deletes it, carry off stops it. In a new session, the first prompt asks whether to pick up where the last one stopped.',
133].join('\n')
134
135const CARRY_OFF = [
136 'Session trail: OFF. Nothing more is recorded.',
137 'What was kept stays until /p_polish carry clear (this project) or carry clear all (every project) deletes it.',
138].join('\n')
139
140const NOTHING_WAITING = 'Nothing from an earlier session is waiting for this project.'
141
142/**
143 * `/p_polish carry ...`: the session trail and the handoff document, which each
144 * person turns on and asks for themself.
145 */
146export async function onCarry($: EngineInterface, rest: string): Promise<string> {
147 const head = rest.split(/\s+/)[0] ?? ''
148 const tail = rest.slice(head.length).trim()
149
150 if (head === 'on') {
151 await turnTrail($, true)
152
153 return CARRY_ON
154 }
155
156 if (head === 'off') {
157 await turnTrail($, false)
158
159 return CARRY_OFF
160 }
161
162 if (head === 'now') {
163 return startHandoff($, tail)
164 }
165
166 if (head === 'setup') {
167 return setupText($)
168 }
169
170 if (head === 'sessions') {
171 return sessionsText($, tail === 'week' ? 'week' : 'day')
172 }
173
174 if (head === 'take') {
175 return takeText($, tail)
176 }
177
178 // What an earlier session left, taken or put by without waiting to be asked.
179 if (head === 'use' || head === 'skip') {
180 const handoff = await handoffOffer($, false)
181 const trail = await offerOf($, false)
182
183 if (head === 'skip') {
184 if (handoff === undefined && trail === undefined) {
185 return NOTHING_WAITING
186 }
187
188 await spend($, trail, handoff)
189 await update($, carryArmed, () => null)
190
191 return 'Skipped. It will not be offered again; carry show still prints it.'
192 }
193
194 const want =
195 tail === 'trail' || tail === 'handoff'
196 ? tail
197 : handoff !== undefined
198 ? 'handoff'
199 : 'trail'
200
201 if (want === 'handoff' ? handoff === undefined : trail === undefined) {
202 return NOTHING_WAITING
203 }
204
205 await update($, carryArmed, () => want)
206
207 return want === 'handoff' && handoff !== undefined
208 ? `The handoff document of the earlier session (/${handoff.command}) will be added to your next prompt, as notes to check against the files.`
209 : `The trail of the earlier session (${trail === undefined ? '' : summaryOf(trail.trail)}) will be added to your next prompt, as notes to check against the files.`
210 }
211
212 if (head === 'clear') {
213 const count = await clearTrails($, tail === 'all')
214
215 return count === 0
216 ? 'Nothing was kept.'
217 : `Session trail and handoff document deleted${tail === 'all' ? ' for every project' : ' for this project'}.`
218 }
219
220 const trails = await readTrails($)
221
222 if (head === 'show' && tail === 'handoff') {
223 const handoff = await readHandoff($)
224
225 return handoff === undefined
226 ? 'No handoff document is kept for this project. /p_polish carry now writes one.'
227 : `Handoff document, written by ${authorOf(handoff.command)}:\n\n${handoff.text}`
228 }
229
230 if (head === 'show') {
231 if (trails.current !== undefined && trails.current.prompts.length > 0) {
232 return renderOf(trails.current)
233 }
234
235 if (trails.previous !== undefined) {
236 return `Nothing yet in this session. The session before:\n\n${renderOf(trails.previous)}`
237 }
238
239 return trails.current === undefined
240 ? 'No session trail is kept for this project.'
241 : renderOf(trails.current)
242 }
243
244 const handoff = await readHandoff($)
245
246 return [
247 `Session trail: ${(await isTrailOn($)) ? 'ON' : 'OFF (it starts off; each person turns it on with /p_polish carry on)'}.`,
248 trails.current === undefined
249 ? 'This session: nothing kept.'
250 : `This session: ${summaryOf(trails.current)}.`,
251 ...(trails.previous === undefined
252 ? []
253 : [`The session before: ${summaryOf(trails.previous)}.`]),
254 handoff === undefined
255 ? 'Handoff document: none (carry now writes one with an installed handoff skill).'
256 : `Handoff document: from /${handoff.command}${handoff.purpose === '' ? '' : `, for: ${handoff.purpose}`}.`,
257 'Commands: carry on | off | now [what the next session is for] | setup | sessions [week] | take <number> [handoff] | show [handoff] | use [trail|handoff] | skip | clear [all]',
258 ].join('\n')
259}
260
261// --- The handoff document ----------------------------------------------------
262
263/**
264 * Starts the installed handoff skill. It is one turn of this session, so it
265 * begins once the session is idle and not inside this command, and it spends
266 * this session's tokens: the answer says so before anything runs.
267 */
268async function startHandoff($: EngineInterface, purpose: string): Promise<string> {
269 if ((await read($, handoffRun)) !== null) {
270 return 'A handoff document is already being written.'
271 }
272
273 const command = await findHandoff($)
274
275 if (command === undefined) {
276 return HANDOFF_MISSING
277 }
278
279 await update($, handoffRun, () => ({
280 command,
281 purpose,
282 isStarted: false,
283 startedAt: 0,
284 }))
285 // The engine refuses to run a command from inside a command's own hook (it
286 // would wait on the turn the hook holds): it is run after the hook has returned.
287 $.clock.after(RUN_AFTER_MS, () => {
288 void $.command.run({ command, args: purpose }).catch(async (error: unknown) => {
289 await update($, handoffRun, () => null)
290 $.ui.toast(`/${command} could not be run: ${String(error).slice(0, 200)}`)
291 })
292 })
293
294 return [
295 `Running /${command}${purpose === '' ? '' : ` for: ${purpose}`}.`,
296 "This is one turn of this session, so it uses this session's tokens. When it ends, the document is kept here (keys and personal details masked), and the first prompt of your next session in this project offers it.",
297 ].join('\n')
298}
299
300/** A skill's prompt was expanded: the handoff skill has begun its turn. */
301export async function onSkill($: EngineInterface, skill: string): Promise<void> {
302 const run = await read($, handoffRun)
303
304 if (run !== null && !run.isStarted && run.command === skill) {
305 const startedAt = await $.clock.now()
306
307 await update($, handoffRun, () => ({ ...run, isStarted: true, startedAt }))
308 }
309}
310
311/** The handoff turn ended: the file the skill wrote is kept as this project's document. */
312async function finishHandoff(
313 $: EngineInterface,
314 run: { command: string; purpose: string; startedAt: number },
315 answer: string,
316 isAborted: boolean,
317): Promise<void> {
318 await update($, handoffRun, () => null)
319
320 if (isAborted) {
321 $.ui.toast('Handoff stopped. Nothing was kept.')
322
323 return
324 }
325
326 const messages = await $.session.messages().catch(() => [])
327 const text = await recoverHandoff(
328 $,
329 candidatesOf(messages, answer),
330 run.startedAt,
331 )
332
333 if (text === undefined) {
334 $.ui.toast(
335 'Handoff ended, but its file could not be found. Nothing kept.',
336 )
337
338 return
339 }
340
341 await saveHandoff($, run, text)
342 $.ui.toast('Handoff document kept · your next session will offer it.')
343}
344
345/** A turn of the main conversation ended: the handoff skill's, or one the trail takes. */
346export async function onTurnEnd(
347 $: EngineInterface,
348 answer: string,
349 isAborted: boolean,
350): Promise<void> {
351 const run = await read($, handoffRun)
352
353 if (run !== null && run.isStarted) {
354 await finishHandoff($, run, answer, isAborted)
355
356 return
357 }
358
359 await recordTurn($, isAborted ? '' : answer)
360}
361
362// --- Picking it up in a new session -------------------------------------------
363
364/** A prompt that is going to the session, as it goes: kept in the trail if it is the person's own words. */
365export async function onSent(
366 $: EngineInterface,
367 e: PromptSubmitInput,
368): Promise<void> {
369 if (
370 e.origin.kind === 'composer' &&
371 e.command === undefined &&
372 e.isMeta !== true
373 ) {
374 await recordPrompt($, e.text)
375 }
376}
377
378/** The answers to the question of picking up an earlier session. */
379const CARRY = {
380 handoff: 'Add the handoff document',
381 trail: 'Add the trail',
382 skip: 'Skip',
383} as const
384
385const cutTo = (text: string, limit: number): string =>
386 text.length > limit ? `${text.slice(0, limit)}…` : text
387
388const carryQuestion = (
389 trail: Offer | undefined,
390 handoff: Handoff | undefined,
391): string =>
392 [
393 'Pick up where your last session in this project stopped?',
394 '',
395 ...(handoff === undefined
396 ? []
397 : [
398 `Handoff document (/${handoff.command})${handoff.purpose === '' ? '' : ` for: ${handoff.purpose}`}: ${handoff.text.length.toLocaleString('en-US')} characters.`,
399 ]),
400 ...(trail === undefined
401 ? []
402 : [
403 `Session trail kept on this computer: ${summaryOf(trail.trail)}.`,
404 `Your last prompt there: ${cutTo(trail.trail.prompts.at(-1) ?? '', 120)}`,
405 ]),
406 '',
407 'Adding one attaches it to this prompt as notes for the model to check against the files. Keys and personal details are masked.',
408 ].join('\n')
409
410/** What the person decided about what an earlier session left, and what it was. */
411export type Carry = {
412 trail?: Offer
413 handoff?: Handoff
414 block: string | null
415}
416
417/**
418 * The first prompt of a session, when an earlier session of this project left
419 * a handoff document or, for a person who turned the trail on, a trail: asks
420 * which to add, if any. Asked before the polish, because it is about the
421 * session and not the prompt. A question nobody could be asked leaves a hint
422 * and the command, and one put away is a Skip. Nothing is attached or spent
423 * here: the prompt may still be stopped.
424 */
425export async function onCarryOver(
426 $: EngineInterface,
427 e: PromptSubmitInput,
428): Promise<Carry | undefined> {
429 if (
430 e.origin.kind !== 'composer' ||
431 e.command !== undefined ||
432 e.isMeta === true
433 ) {
434 return undefined
435 }
436
437 const armed = await read($, carryArmed)
438
439 if (armed !== null) {
440 await update($, carryArmed, () => null)
441
442 if (armed === 'handoff') {
443 const handoff = await handoffOffer($, false)
444
445 return handoff === undefined
446 ? undefined
447 : { handoff, block: handoffBlock(handoff) }
448 }
449
450 const trail = await offerOf($, false)
451
452 return trail === undefined
453 ? undefined
454 : { trail, block: blockOf(trail.trail) }
455 }
456
457 const handoff = await handoffOffer($, true)
458 const found = await offerOf($, true)
459 // planning-with-files recovers a session from its own files: a trail would say it twice.
460 const trail = found !== undefined && !(await isPlanning($)) ? found : undefined
461
462 if (handoff === undefined && trail === undefined) {
463 return undefined
464 }
465
466 const offered = {
467 ...(trail === undefined ? {} : { trail }),
468 ...(handoff === undefined ? {} : { handoff }),
469 }
470 const askedAt = await $.clock.now()
471 const answer = await $.ui
472 .ask(carryQuestion(trail, handoff), {
473 header: 'Carry over',
474 options: [
475 ...(handoff === undefined ? [] : [CARRY.handoff]),
476 ...(trail === undefined ? [] : [CARRY.trail]),
477 CARRY.skip,
478 ],
479 })
480 .catch(() => undefined)
481
482 if (answer === undefined) {
483 if ((await $.clock.now()) - askedAt < UNASKED_MS) {
484 $.ui.toast('Last session is kept · /p_polish carry use adds it.')
485
486 return undefined
487 }
488
489 return { ...offered, block: null }
490 }
491
492 return {
493 ...offered,
494 block:
495 answer === CARRY.handoff && handoff !== undefined
496 ? handoffBlock(handoff)
497 : answer === CARRY.trail && trail !== undefined
498 ? blockOf(trail.trail)
499 : null,
500 }
501}
502
503/** The offer is spent, taken or skipped: neither is offered again. */
504async function spend(
505 $: EngineInterface,
506 trail: Offer | undefined,
507 handoff: Handoff | undefined,
508): Promise<void> {
509 if (trail !== undefined) {
510 await markOffered($, trail)
511 }
512
513 if (handoff !== undefined) {
514 await markHandoffOffered($, handoff)
515 }
516}
517
518/** The prompt goes on: the offer is spent, and what was taken goes with it. */
519export async function onCarried(
520 $: EngineInterface,
521 carry: Carry | undefined,
522): Promise<readonly string[]> {
523 if (carry === undefined) {
524 return []
525 }
526
527 await spend($, carry.trail, carry.handoff)
528
529 return carry.block === null ? [] : [carry.block]
530}
531
532// --- When the context runs full ------------------------------------------------
533
534const MEASURE = { now: 'Write the handoff', later: 'Not now' } as const
535
536/**
537 * The context passed the threshold: once in a session, asks whether to write a
538 * handoff document, or says how to get the skill that writes one. It asks and
539 * never runs on its own. The work is detached: the engine's measuring does not
540 * wait for the person's answer.
541 */
542export async function onMeasure(
543 $: EngineInterface,
544 percent: number | undefined,
545 changed: readonly string[],
546): Promise<void> {
547 if (percent === undefined || percent < THRESHOLD || !changed.includes('context')) {
548 return
549 }
550
551 const session = await $.session.id()
552
553 if ((await read($, measureAsked)) === session) {
554 return
555 }
556
557 await update($, measureAsked, () => session)
558
559 if ((await read($, handoffRun)) !== null) {
560 return
561 }
562
563 const command = await findHandoff($)
564
565 if (command === undefined) {
566 $.ui.toast(`Context is ${percent}% full · handoff skill: /p_polish carry setup`)
567
568 return
569 }
570
571 void askHandoff($, command, percent).catch(() => undefined)
572}
573
574async function askHandoff(
575 $: EngineInterface,
576 command: string,
577 percent: number,
578): Promise<void> {
579 const askedAt = await $.clock.now()
580 const answer = await $.ui
581 .ask(
582 `Context is ${percent}% full.\n\nWrite a handoff document now, so a new session can pick up from here? It runs /${command} as one turn of this session, which uses this session's tokens.`,
583 { header: 'Context', options: [MEASURE.now, MEASURE.later] },
584 )
585 .catch(() => undefined)
586
587 if (answer === MEASURE.now) {
588 await startHandoff($, '')
589 } else if (answer === undefined && (await $.clock.now()) - askedAt < UNASKED_MS) {
590 $.ui.toast(`Context is ${percent}% full · /p_polish carry now writes a handoff.`)
591 }
592}
593
594
595// --- Picking up an earlier session ---------------------------------------------
596
597/** The list the pane draws: what is open, picked and handed over, told against now and this session. */
598export async function sessionsView($: EngineInterface): Promise<SessionsView> {
599 const state = await read($, sessions)
600 const current = await $.session.id().catch(() => '')
601
602 // Each entry is `session|id|title`: the sessions handed over to the one now open.
603 const done = state.done
604 .filter(entry => entry.startsWith(`${current}|`))
605 .map(entry => entry.slice(current.length + 1))
606 .map(entry => {
607 const at = entry.indexOf('|')
608
609 return { id: entry.slice(0, at), title: entry.slice(at + 1) }
610 })
611
612 return { ...state, done, now: await $.clock.now() }
613}
614
615async function loadSessions($: EngineInterface): Promise<void> {
616 const state = await read($, sessions)
617
618 await update($, sessions, s => ({ ...s, isLoading: true }))
619
620 try {
621 const handoff = await readHandoff($)
622 const rows = await listSessions(
623 $,
624 state.range === 'day' ? DAY_MS : WEEK_MS,
625 handoff?.session,
626 )
627
628 await update($, sessions, s => ({ ...s, rows, isLoading: false }))
629 } catch {
630 await update($, sessions, s => ({ ...s, rows: [], isLoading: false }))
631 }
632}
633
634/** The pane's Earlier sessions row: opens the list, reading the files then and not before, or folds it. */
635export async function toggleSessions($: EngineInterface): Promise<void> {
636 const state = await read($, sessions)
637
638 if (state.isOpen) {
639 await update($, sessions, s => ({ ...s, isOpen: false, picked: null }))
640
641 return
642 }
643
644 await update($, sessions, s => ({ ...s, isOpen: true, rows: null, picked: null }))
645 await loadSessions($)
646}
647
648/** Opens the list if it is not open yet, reading the session files then. */
649export async function openSessions($: EngineInterface): Promise<void> {
650 if (!(await read($, sessions)).isOpen) {
651 await toggleSessions($)
652 }
653}
654
655/** The last day, or up to a week. */
656export async function setRange(
657 $: EngineInterface,
658 range: SessionsState['range'],
659): Promise<void> {
660 await update($, sessions, s => ({ ...s, range, rows: null, picked: null }))
661 await loadSessions($)
662}
663
664/** Opens a session of the list for a closer look, or folds it. Notes are given unless it has a handoff document. */
665export async function pickSession($: EngineInterface, id: string): Promise<void> {
666 await update($, sessions, s => {
667 const row = s.rows?.find(r => r.id === id)
668 const kind: SessionsState['kind'] = row?.hasHandoff === true ? 'handoff' : 'notes'
669
670 return s.picked === id ? { ...s, picked: null } : { ...s, picked: id, kind }
671 })
672}
673
674export async function setKind(
675 $: EngineInterface,
676 kind: SessionsState['kind'],
677): Promise<void> {
678 await update($, sessions, s => ({ ...s, kind }))
679}
680
681/**
682 * Hands an earlier session over to this one: its notes (or its handoff
683 * document) are appended to this conversation as a row the person does not
684 * type, which the model reads with the next prompt. No turn is made here.
685 */
686async function handOver(
687 $: EngineInterface,
688 id: string,
689 kind: SessionsState['kind'],
690): Promise<{ text: string; toast: string }> {
691 const fail = (text: string) => ({ text, toast: text.slice(0, 70) })
692 const root = await $.session.root().catch(() => undefined)
693 const state = await read($, sessions)
694 const row = state.rows?.find(r => r.id === id)
695 let block: string
696 let said: string
697
698 if (kind === 'handoff') {
699 const handoff = await readHandoff($)
700
701 if (handoff === undefined || handoff.session !== id) {
702 return fail('No handoff document is kept for that session.')
703 }
704
705 block = handoffBlock(handoff)
706 said = 'its handoff document'
707 await markHandoffOffered($, handoff)
708 } else {
709 const stored = await storedTrailOf($, id)
710 const trail =
711 stored?.trail ?? (await notesOf($, id, nameOf(root ?? '')))
712
713 if (trail === undefined) {
714 return fail('That session could not be read.')
715 }
716
717 block = blockOf(trail)
718 said = 'its notes'
719
720 if (stored !== undefined) {
721 await markOffered($, stored)
722 }
723 }
724
725 const appended = await $.session.append({
726 message: { type: 'user', content: [{ type: 'text', text: block }] },
727 })
728
729 if ('deny' in appended) {
730 return fail(`It could not be handed over: ${String(appended.deny).slice(0, 160)}`)
731 }
732
733 const current = await $.session.id()
734 const title = row?.title ?? id
735
736 await update($, sessions, s => ({
737 ...s,
738 done: [...s.done.filter(entry => entry !== `${current}|${id}|${title}`), `${current}|${id}|${title}`],
739 }))
740
741 return {
742 text: `Handed over ${said} of "${title}". The model reads it with your next prompt.`,
743 toast: `Handed over "${title.length > 32 ? `${title.slice(0, 32)}…` : title}" · send your next prompt.`,
744 }
745}
746
747/** The pane's button: hands over the session that is opened, in the form that is chosen. */
748export async function takeSession($: EngineInterface): Promise<void> {
749 const state = await read($, sessions)
750
751 if (state.picked === null) {
752 return
753 }
754
755 try {
756 $.ui.toast((await handOver($, state.picked, state.kind)).toast)
757 } catch (error) {
758 $.ui.toast(`It could not be handed over: ${String(error).slice(0, 160)}`)
759 }
760}
761
762const numbered = (rows: readonly SessionRow[], now: number): string =>
763 rows
764 .map(
765 (row, i) =>
766 `${i + 1}. ${agoOf(now, row.at)} · ${row.title}${row.files > 0 ? ` (${row.files} ${row.files === 1 ? 'file' : 'files'}${row.hasHandoff ? ', handoff document' : ''})` : row.hasHandoff ? ' (handoff document)' : ''}${row.last !== '' && row.last !== row.title ? `\n last prompt: ${row.last}` : ''}`,
767 )
768 .join('\n')
769
770/** `/p_polish carry sessions [week]`: the sessions of this project from the last day, or up to a week. */
771async function sessionsText(
772 $: EngineInterface,
773 range: SessionsState['range'],
774): Promise<string> {
775 await update($, sessions, s => ({ ...s, range, rows: null, picked: null }))
776 await loadSessions($)
777
778 const state = await read($, sessions)
779 const rows = state.rows ?? []
780 const now = await $.clock.now()
781 const where = range === 'day' ? 'the last 24 hours' : 'the last 7 days'
782
783 if (rows.length === 0) {
784 return [
785 `No earlier session of this project in ${where}.`,
786 ...(range === 'day' ? ['Not here? /p_polish carry sessions week'] : []),
787 ].join('\n')
788 }
789
790 return [
791 `Earlier sessions of this project, ${where}:`,
792 numbered(rows, now),
793 '',
794 ...(range === 'day' ? ['Not here? /p_polish carry sessions week'] : []),
795 'Hand one over to this session: /p_polish carry take <number> [handoff]',
796 ].join('\n')
797}
798
799/** `/p_polish carry take <number> [handoff]`: hands the numbered session of the last listing over to this one. */
800async function takeText($: EngineInterface, rest: string): Promise<string> {
801 const [which = '', form = ''] = rest.split(/\s+/)
802 const state = await read($, sessions)
803 const rows = state.rows
804
805 if (rows === null) {
806 return 'List the sessions first: /p_polish carry sessions'
807 }
808
809 const row = /^\d+$/.test(which)
810 ? rows[Number(which) - 1]
811 : rows.find(r => which !== '' && r.id.startsWith(which))
812
813 if (row === undefined) {
814 return `No session ${which === '' ? 'was named' : `"${which}"`} in the last listing. /p_polish carry sessions shows it.`
815 }
816
817 return (await handOver($, row.id, form === 'handoff' ? 'handoff' : 'notes')).text
818}
819hooks/band.tsx 341 lines1// The pane as a band right above the prompt box, in the Claude desktop app.
2//
3// The app gives this band about eleven lines and scrolls what is past them
4// with the scroll bar hidden, so the band is built to stay inside that, in
5// every state, and its places do not move:
6//
7// head the name at the left, which minimizes the band; AUTO and the state at the top right
8// settings the session model, the polish model and the effort, as selects
9// stage one place, of one height, for what is going on: the loading mark
10// while a polish runs, the start of the polish in review, with
11// its versions in its head
12// foot what to do now at the left (Prompt Polish, the three answers, or
13// Stop), at the right Full view and History
14//
15// A list a select opens takes the place of the stage and the foot while it is
16// open, so the band is no taller for it. While a polish runs the settings are
17// said where the selects were, so the band is as high in review as it was then. The polish is read in full in the
18// pane beside the conversation, which opens for the review and has the room:
19// the band is for deciding, the pane for reading.
20//
21// The band can be minimized: its name is the button, with a chevron after it.
22// Minimized, it is not drawn above the prompt box at all (the app frames
23// whatever is drawn there in a box of its own, however small the thing), and a
24// chip in the prompt's footer opens it again (`bandChip`). The person's last
25// choice is kept for the next session (core.ts).
26//
27// It is made of the View core.ts reads and the controls of kit.tsx, as the
28// pane is (desktop.tsx), and its controls call the same Act. The band is every
29// mod's, so what the others draw there (`theirs`) is kept under this one.
30import type { RenderElement } from 'claude-code'
31
32import { kitOf } from './kit'
33import type { Table } from './kit'
34import { EFFORTS } from './polish'
35import type { Act, Layout, Marks, View } from './view'
36
37// The stage is this many lines high, whatever is in it.
38const STAGE = 4.5
39// The polish in review is cut to this many lines.
40const SNIPPET_LINES = 2
41// More chips than this make a tray taller than the band has room for.
42const MAX_CHIPS = 15
43
44export const desktopBand = (
45 table: Table,
46 view: View,
47 act: Act,
48 layout: Layout,
49 marks: Marks,
50 theirs: unknown,
51): RenderElement => {
52 const { Box, Button, Text } = table
53 const k = kitOf(table, view, act, marks)
54 const isListed = !view.isRunning && view.menu !== null
55
56 // The name is the way to minimize the band: a chevron after it, and a click
57 // anywhere on the two. Under a catcher its words are there out of sight, for
58 // the keys and for what reads the tree; with no catcher the button says them.
59 const name = k.control(
60 'minimize-box',
61 'minimize',
62 [
63 k.title,
64 k.icon('down', 'Minimize'),
65 k.isCaught ? (
66 <Box key="minimize-words" width={0} overflow="hidden">
67 <Button key="minimize" plain onPress={() => act.band(false)}>
68 Minimize
69 </Button>
70 </Box>
71 ) : (
72 <Button key="minimize" plain onPress={() => act.band(false)}>
73 Minimize ▾
74 </Button>
75 ),
76 ],
77 { columnGap: 1, paddingY: 0.5 },
78 )
79
80 // A pick folds its list, as a select's does.
81 const chooseModel = (value: string) => {
82 act.model(value)
83 act.done()
84 }
85 const chooseEffort = (value: string) => {
86 act.effort(value)
87 act.done()
88 }
89
90 // The name at the left. At the right AUTO, and the state, which moves while
91 // a polish runs: the state is always the last thing on the line.
92 const head = (
93 <Box
94 key="band-head"
95 alignItems="center"
96 justifyContent="space-between"
97 columnGap={2}
98 >
99 {name}
100 <Box alignItems="center" columnGap={2} flexWrap="wrap">
101 {!view.isRunning && k.toggle('auto', 'AUTO', view.isOn, act.auto)}
102 {!view.isRunning &&
103 k.toggle('trail', 'TRAIL', view.isTrailing, act.trail)}
104 {k.status}
105 </Box>
106 </Box>
107 )
108
109 // Three selects fill the line, and wrap whole to the next when it is narrow.
110 // While a polish runs they say what runs, in the same place and as high.
111 const settings = (
112 <Box
113 key="band-settings"
114 columnGap={1}
115 rowGap={1}
116 flexWrap="wrap"
117 alignItems="center"
118 >
119 {view.isRunning && k.readout('target-now', 'Session', view.targetLabel)}
120 {view.isRunning && k.readout('polisher-now', 'Polish', view.model)}
121 {view.isRunning && k.readout('effort-now', 'Effort', view.effort)}
122 {!view.isRunning && k.select(
123 'target',
124 view.targetLabel,
125 view.menu === 'target',
126 () => act.menu('target'),
127 'Session',
128 )}
129 {!view.isRunning && k.select(
130 'polisher',
131 view.model,
132 view.menu === 'polisher',
133 () => act.menu('polisher'),
134 'Polish',
135 )}
136 {!view.isRunning && k.select(
137 'effort',
138 view.effort,
139 view.menu === 'effort',
140 () => act.menu('effort'),
141 'Effort',
142 )}
143 </Box>
144 )
145
146 // The models a tray has room for. A person with more picks one by name.
147 const models = view.models.slice(0, MAX_CHIPS)
148 const unlisted = view.models.length - models.length
149
150 // The list of the one that is open, under the settings; a pick folds it.
151 const list = !isListed ? null : view.menu === 'target' ? (
152 <Box key="band-list" flexDirection="column" rowGap={1} alignItems="stretch">
153 {k.options('target', view.targets, view.choice, act.target)}
154 <Box key="guide-part" flexDirection="column" alignItems="stretch">
155 {k.row('guide', `${view.guide} guide`, act.guide, {
156 before: 'book',
157 isOpen: view.isGuideShown,
158 })}
159 {view.isGuideShown && (
160 <Box key="about">
161 <Text dimColor wrap="wrap">
162 {view.about}
163 </Text>
164 </Box>
165 )}
166 </Box>
167 </Box>
168 ) : view.menu === 'polisher' ? (
169 <Box key="band-list" flexDirection="column" rowGap={0.5} alignItems="stretch">
170 {k.options(
171 'model',
172 models.map(value => ({ value, label: value })),
173 view.model,
174 chooseModel,
175 )}
176 {unlisted > 0 && (
177 <Box key="unlisted">
178 <Text color="subtle" wrap="truncate">
179 {`${unlisted} more: /polish model <name> picks any`}
180 </Text>
181 </Box>
182 )}
183 </Box>
184 ) : (
185 <Box key="band-list" flexDirection="column" alignItems="stretch">
186 {k.options(
187 'effort',
188 EFFORTS.map(value => ({ value, label: value })),
189 view.effort,
190 chooseEffort,
191 )}
192 </Box>
193 )
194
195 // The one place for what is going on, and one height for it: the loading
196 // mark while a polish runs, and in review the start of the polish; a retry
197 // runs over a polish on show, which the mark takes the place of.
198 const stage =
199 isListed ||
200 (!view.isRunning && view.preview === null && !view.isAnswering) ? null : (
201 <Box
202 key="band-stage"
203 flexDirection="column"
204 minHeight={STAGE}
205 alignItems="stretch"
206 >
207 {view.isRunning
208 ? k.working
209 : view.isAnswering
210 ? k.waiting
211 : view.preview !== null &&
212 k.snippet(
213 'polished',
214 view.preview,
215 SNIPPET_LINES,
216 Math.floor(layout.columns * SNIPPET_LINES * 0.8),
217 k.pager,
218 )}
219 </Box>
220 )
221
222 // What to do now, at the left: the button that makes a polish, the three
223 // answers to a polish on show, or Stop. At the right the way to read the
224 // polish in full, and the record, which the pane lists. The row is always
225 // there, and so is each end of it.
226 const left = view.isRunning ? (
227 k.stop
228 ) : view.isAnswering ? null : view.preview !== null ? (
229 <Box alignItems="center" columnGap={1} rowGap={1} flexWrap="wrap">
230 {k.button('apply', 'Apply Polish', act.apply, {
231 variant: 'primary',
232 before: 'check',
233 isFirst: true,
234 })}
235 {k.button('refresh', 'Retry Polish', act.retry, {
236 variant: 'secondary',
237 before: 'retry',
238 })}
239 {k.button('discard', 'Keep Original', act.keep, {
240 variant: 'secondary',
241 before: 'close',
242 })}
243 </Box>
244 ) : (
245 <Box alignItems="center" columnGap={1} rowGap={1} flexWrap="wrap">
246 {k.button('polish', 'Prompt Polish', act.polish, {
247 variant: 'primary',
248 before: 'wand',
249 })}
250 {view.draft !== null &&
251 k.button('restore', 'Undo Apply', act.undo, {
252 variant: 'secondary',
253 before: 'undo',
254 })}
255 </Box>
256 )
257 const foot = isListed ? null : (
258 <Box
259 key="action-row"
260 alignItems="center"
261 justifyContent="space-between"
262 columnGap={2}
263 rowGap={1}
264 flexWrap="wrap"
265 >
266 {left}
267 <Box alignItems="center" columnGap={1} flexShrink={0}>
268 {view.preview !== null &&
269 !view.isRunning &&
270 k.button('panel', 'Full view', act.panel, { variant: 'secondary' })}
271 {!view.isRunning &&
272 view.preview === null &&
273 k.button('sessions', 'Earlier sessions', act.sessionsPanel, {
274 variant: 'secondary',
275 })}
276 {k.button(
277 'log',
278 view.lines.length === 0 ? 'History' : `History ${view.lines.length}`,
279 act.history,
280 { variant: 'secondary' },
281 )}
282 </Box>
283 </Box>
284 )
285
286 return (
287 <Box key="band" flexDirection="column" rowGap={1} alignItems="stretch">
288 {k.card(
289 'band-card',
290 <Box flexDirection="column" rowGap={1} alignItems="stretch">
291 {head}
292 {settings}
293 {list}
294 {stage}
295 {foot}
296 </Box>,
297 )}
298 {theirs as RenderElement}
299 </Box>
300 )
301}
302
303/**
304 * The band when it is minimized: one chip in the prompt's footer, among the
305 * labels the engine draws there (`modes`, kept). The app draws that site as one
306 * line of words and small buttons, and no drawings, so the state is a word on
307 * the button and a colored dot after it. Pressing the button opens the band.
308 */
309export const bandChip = (
310 table: Table,
311 view: View,
312 act: Act,
313 modes: readonly string[],
314): RenderElement => {
315 const { Box, Button, Text } = table
316 const word =
317 view.phase === 'busy'
318 ? 'Polishing…'
319 : view.phase === 'review'
320 ? 'Review'
321 : 'Prompt Polish'
322 const dot =
323 view.phase === 'busy' ? 'claude' : view.phase === 'review' ? 'suggestion' : 'success'
324
325 return (
326 <Box key="band-chip" alignItems="center" columnGap={1}>
327 <Button key="expand" plain onPress={() => act.band(true)}>
328 {word}
329 </Button>
330 <Box key="state">
331 <Text color={dot}>●</Text>
332 </Box>
333 {modes.length > 0 && (
334 <Box key="modes">
335 <Text dimColor>{modes.join(' & ')}</Text>
336 </Box>
337 )}
338 </Box>
339 )
340}
341hooks/desktop.tsx 554 lines1// The pane as the Claude desktop app draws it beside the conversation: a
2// narrow panel of cards, as the app's own session panel is. The progress of
3// the draft is four steps on a line; the polished prompt is the card that
4// matters in review; the settings fold into a row until asked for; the
5// original sits under a toggle. It is made of the View core.ts reads and the
6// controls of kit.tsx, and its controls call the Act core.ts holds: no state,
7// no engine call here but in `pressed`, which answers a click the catchers
8// post, from this pane and from the band (band.tsx).
9import type { EngineInterface, PluginOptions, RenderElement } from 'claude-code'
10
11import { actsOf, PANE, viewOf } from './core'
12import { FAINT, kitOf } from './kit'
13import type { Table } from './kit'
14import { agoOf } from './sessions'
15import type { Act, Layout, Marks, View } from './view'
16
17export const desktopPane = (
18 table: Table,
19 view: View,
20 act: Act,
21 layout: Layout,
22 marks: Marks,
23): RenderElement => {
24 const { Box, Button, Text } = table
25 const k = kitOf(table, view, act, marks)
26 // AUTO leads: it is the one thing in the line that changes what Enter does,
27 // and a narrow pane cuts the line at its end.
28 const summary = `AUTO ${view.isOn ? 'on' : 'off'} · ${view.guide} · ${view.model} (${view.effort})`
29
30 // One setting: its name over its control.
31 const field = (name: string, children: JSX.Children) => (
32 <Box
33 key={`field-${name}`}
34 flexDirection="column"
35 rowGap={0.5}
36 alignItems="stretch"
37 >
38 <Text dimColor>{name}</Text>
39 {children}
40 </Box>
41 )
42
43 // The head, the steps, and what to do now: the one button that makes a
44 // polish, or the loading mark while it runs. In review the card under
45 // holds the answers.
46 const statusCard = k.card(
47 'status-card',
48 <Box flexDirection="column" rowGap={1.5} alignItems="stretch">
49 <Box
50 key="head"
51 alignItems="center"
52 justifyContent="space-between"
53 columnGap={2}
54 >
55 {k.title}
56 {k.status}
57 </Box>
58 {k.stepper()}
59 {view.isRunning && k.loader}
60 {view.isAnswering && !view.isRunning && k.waiting}
61 {!view.isRunning && !view.isAnswering && view.preview === null && (
62 <Box
63 key="action-row"
64 flexDirection="column"
65 rowGap={1}
66 alignItems="stretch"
67 >
68 {k.button('polish', 'Prompt Polish', act.polish, {
69 variant: 'primary',
70 before: 'wand',
71 isGrown: true,
72 })}
73 {view.draft !== null &&
74 k.button('restore', 'Undo Apply', act.undo, {
75 variant: 'secondary',
76 before: 'undo',
77 })}
78 </Box>
79 )}
80 </Box>,
81 )
82
83 // The polish on show, with its versions, the draft it was made from under a
84 // toggle, and the answers: apply it, make another, or keep the draft. A
85 // retry runs over it, and it stays.
86 const reviewCard =
87 view.preview === null
88 ? null
89 : k.card(
90 'review-card',
91 <Box flexDirection="column" rowGap={1} alignItems="stretch">
92 {k.pager !== null && (
93 <Box key="pager-row" justifyContent="flex-end">
94 {k.pager}
95 </Box>
96 )}
97 {k.words('polished', view.preview, true, 'Polished prompt')}
98 {k.row(
99 'original-toggle',
100 view.isOriginalShown
101 ? 'Hide original'
102 : `Show original · ${k.chars(view.draft ?? '')}`,
103 act.original,
104 { isOpen: view.isOriginalShown },
105 )}
106 {view.isOriginalShown &&
107 k.words('original', view.draft ?? '', false, 'Original prompt')}
108 {!view.isRunning && (
109 <Box
110 key="action-row"
111 flexDirection="column"
112 rowGap={1}
113 alignItems="stretch"
114 >
115 {k.button('apply', 'Apply Polish', act.apply, {
116 variant: 'primary',
117 before: 'check',
118 isFirst: true,
119 isGrown: true,
120 })}
121 <Box columnGap={1} rowGap={1} flexWrap="wrap">
122 {k.button('refresh', 'Retry Polish', act.retry, {
123 variant: 'secondary',
124 before: 'retry',
125 isGrown: true,
126 })}
127 {k.button('discard', 'Keep Original', act.keep, {
128 variant: 'secondary',
129 before: 'close',
130 isGrown: true,
131 })}
132 </Box>
133 </Box>
134 )}
135 </Box>,
136 )
137
138 // The settings, folded to a row that says them in a line and opens them: the
139 // switch, who the prompt is for, who polishes and how hard, and the guide.
140 const settingsCard = view.isRunning
141 ? null
142 : k.card(
143 'settings-card',
144 <Box flexDirection="column" rowGap={1} alignItems="stretch">
145 {k.row('setup', 'Settings', act.setup, {
146 isOpen: view.isSetupShown,
147 ...(view.isSetupShown ? {} : { hint: summary }),
148 })}
149 {view.isSetupShown && (
150 <Box
151 key="settings"
152 flexDirection="column"
153 rowGap={1.5}
154 alignItems="stretch"
155 >
156 <Box key="auto-part" flexDirection="column" alignItems="stretch">
157 {k.toggle('auto', 'AUTO', view.isOn, act.auto)}
158 <Text color={FAINT} wrap="wrap">
159 {view.isOn
160 ? 'Enter polishes first and asks you before sending.'
161 : 'Enter sends right away, with no polish.'}
162 </Text>
163 </Box>
164 <Box key="trail-part" flexDirection="column" alignItems="stretch">
165 {k.toggle('trail', 'TRAIL', view.isTrailing, act.trail)}
166 <Text color={FAINT} wrap="wrap">
167 {view.isTrailing
168 ? 'Keeps your recent prompts on this computer, so a new session can pick up from them. It asks first.'
169 : 'Off. Turn it on to let a new session pick up from this one.'}
170 </Text>
171 </Box>
172 {field(
173 'Session model',
174 <Box flexDirection="column" rowGap={0.5} alignItems="stretch">
175 {k.select('target', view.targetLabel, view.menu === 'target', () =>
176 act.menu('target'),
177 )}
178 {view.menu === 'target' &&
179 k.options('target', view.targets, view.choice, act.target)}
180 </Box>,
181 )}
182 {field(
183 'Polish model',
184 <Box flexDirection="column" rowGap={0.5} alignItems="stretch">
185 {k.select('polisher', view.model, view.menu === 'polisher', () =>
186 act.menu('polisher'),
187 )}
188 {view.menu === 'polisher' &&
189 k.options(
190 'model',
191 view.models.map(value => ({ value, label: value })),
192 view.model,
193 value => {
194 act.model(value)
195 act.done()
196 },
197 )}
198 </Box>,
199 )}
200 {field('Effort', k.segments(view.effort))}
201 <Box key="guide-part" flexDirection="column" alignItems="stretch">
202 {k.row('guide', `${view.guide} guide`, act.guide, {
203 before: 'book',
204 isOpen: view.isGuideShown,
205 })}
206 {view.isGuideShown && (
207 <Box key="about">
208 <Text dimColor wrap="wrap">
209 {view.about}
210 </Text>
211 </Box>
212 )}
213 </Box>
214 </Box>
215 )}
216 </Box>,
217 )
218
219 // The earlier sessions of this project, to pick one up from: a row that opens
220 // the list, the last day or up to a week, and a session opened for a closer
221 // look with a button to hand it over to this one.
222 const sx = view.sessions
223 // Not while a polish runs or waits on an answer: the card is for picking up
224 // an earlier session, and it would only crowd the choice at hand.
225 const sessionsCard =
226 view.isRunning || view.isAnswering || view.preview !== null
227 ? null
228 : k.card(
229 'sessions-card',
230 <Box flexDirection="column" rowGap={1} alignItems="stretch">
231 {k.row('sessions', 'Pick up an earlier session', act.sessions, {
232 isOpen: sx.isOpen,
233 ...(!sx.isOpen && sx.done.length > 0
234 ? { hint: `✓ ${sx.done.length} handed over` }
235 : {}),
236 })}
237 {sx.isOpen && (
238 <Box
239 key="sessions-body"
240 flexDirection="column"
241 rowGap={1}
242 alignItems="stretch"
243 >
244 {sx.done.length > 0 && (
245 <Text key="sessions-done" color="success" wrap="wrap">
246 {`✓ Handed over ${sx.done
247 .map(entry => `“${entry.title.length > 28 ? `${entry.title.slice(0, 28)}…` : entry.title}”`)
248 .join(', ')}. The model reads it with your next prompt.`}
249 </Text>
250 )}
251 {k.segmented(
252 'range',
253 [
254 { value: 'day', label: 'Last 24 hours' },
255 { value: 'week', label: 'Up to 7 days' },
256 ],
257 sx.range,
258 value => act.sessionsRange(value === 'week' ? 'week' : 'day'),
259 )}
260 {sx.isLoading && (
261 <Text key="sessions-loading" color={FAINT}>
262 Reading the sessions…
263 </Text>
264 )}
265 {!sx.isLoading && sx.rows !== null && sx.rows.length === 0 && (
266 <Text key="sessions-none" color={FAINT} wrap="wrap">
267 {sx.range === 'day'
268 ? 'No earlier session in the last 24 hours. Try up to 7 days.'
269 : 'No earlier session in the last 7 days.'}
270 </Text>
271 )}
272 {!sx.isLoading &&
273 (sx.rows ?? []).map(row => {
274 const isPicked = sx.picked === row.id
275 const isDone = sx.done.some(entry => entry.id === row.id)
276 const counts = [
277 row.files > 0
278 ? `${row.files} ${row.files === 1 ? 'file' : 'files'}`
279 : '',
280 row.hasHandoff ? 'handoff' : '',
281 ]
282 .filter(part => part !== '')
283 .join(' · ')
284
285 return (
286 <Box
287 key={`session-${row.id}-item`}
288 flexDirection="column"
289 rowGap={0.5}
290 alignItems="stretch"
291 >
292 {k.control(
293 `session-${row.id}-box`,
294 `session-${row.id}`,
295 // Two lines, so that sessions of one title can be told apart
296 // without opening each: the title, and under it when it was,
297 // what it changed and what was last asked.
298 <Box
299 key="lines"
300 flexDirection="column"
301 flexGrow={1}
302 flexShrink={1}
303 overflow="hidden"
304 alignItems="stretch"
305 >
306 <Box key="title" overflow="hidden">
307 <Button
308 key={`session-${row.id}`}
309 plain
310 onPress={() => act.sessionPick(row.id)}
311 >
312 {`${isPicked ? '▾' : '▸'} ${row.title}${isDone ? ' ✓' : ''}`}
313 </Button>
314 </Box>
315 <Box key="detail" paddingLeft={2} overflow="hidden">
316 <Text color={FAINT} wrap="truncate">
317 {[
318 agoOf(sx.now, row.at),
319 counts,
320 // Opened, the whole of it is said just below.
321 !isPicked && row.last !== '' && row.last !== row.title
322 ? row.last
323 : '',
324 ]
325 .filter(part => part !== '')
326 .join(' · ')}
327 </Text>
328 </Box>
329 </Box>,
330 { paddingY: 0.5 },
331 3,
332 )}
333 {isPicked && (
334 <Box
335 key={`session-${row.id}-detail`}
336 flexDirection="column"
337 rowGap={1}
338 alignItems="stretch"
339 paddingLeft={2}
340 >
341 {row.last !== '' && (
342 <Text color={FAINT} wrap="wrap">
343 {`Last prompt: ${row.last}`}
344 </Text>
345 )}
346 {row.hasHandoff &&
347 k.segmented(
348 'kind',
349 [
350 { value: 'notes', label: 'Notes' },
351 { value: 'handoff', label: 'Handoff document' },
352 ],
353 sx.kind,
354 value => act.sessionKind(value === 'handoff' ? 'handoff' : 'notes'),
355 )}
356 <Box key="take-row">
357 {k.button(
358 'session-take',
359 isDone ? 'Hand over again' : 'Hand over to this session',
360 act.sessionTake,
361 { variant: 'primary' },
362 )}
363 </Box>
364 <Text key="take-note" color={FAINT} wrap="wrap">
365 The model reads it with your next prompt. Keys and personal details are masked.
366 </Text>
367 </Box>
368 )}
369 </Box>
370 )
371 })}
372 </Box>
373 )}
374 </Box>,
375 )
376
377 return (
378 <Box
379 key="pane"
380 flexDirection="column"
381 rowGap={1}
382 alignItems="stretch"
383 {...(layout.isDocked ? { minHeight: Math.max(1, layout.bodyRows) } : {})}
384 >
385 {statusCard}
386 {reviewCard}
387 {settingsCard}
388 {sessionsCard}
389 {layout.isDocked && <Box key="spacer" flexGrow={1} />}
390 {k.card('history-card', k.history)}
391 </Box>
392 )
393}
394
395/** The key a catcher posted (hit.tsx), when the post is one. */
396function pressOf(data: unknown): string | undefined {
397 return typeof data === 'object' &&
398 data !== null &&
399 'press' in data &&
400 typeof data.press === 'string'
401 ? data.press
402 : undefined
403}
404
405/**
406 * Does what the control keyed `key` does, when the pane or band as it stands
407 * draws that control. A catcher's post is input from the app, and may name a
408 * control a redraw has taken away since the click began. The band keeps its
409 * settings in view; the pane folds them under its Settings row.
410 */
411async function pressed(
412 $: EngineInterface,
413 options: PluginOptions,
414 key: string,
415 isBand: boolean,
416): Promise<void> {
417 const view = await viewOf($, options)
418 const act = actsOf($, options)
419
420 // Drawn in every state: the record. The band has no list of it: it opens the pane.
421 if (key === 'log') {
422 return isBand ? act.history() : act.log()
423 }
424
425 // The band's own two, drawn in every state: minimizing it, and opening it again.
426 if (isBand && (key === 'minimize' || key === 'expand')) {
427 return act.band(key === 'expand')
428 }
429
430 // While a polish runs the settings and the working row are gone, and so is the list of sessions.
431 if (!view.isRunning && key === 'sessions') {
432 return isBand ? act.sessionsPanel() : act.sessions()
433 }
434
435 if (!isBand && !view.isRunning && view.sessions.isOpen) {
436 const sx = view.sessions
437
438 if (key === 'range-day' || key === 'range-week') {
439 return act.sessionsRange(key === 'range-day' ? 'day' : 'week')
440 }
441
442 if (key === 'session-take') {
443 return sx.picked === null ? undefined : act.sessionTake()
444 }
445
446 if (key === 'kind-notes' || key === 'kind-handoff') {
447 return sx.picked === null ? undefined : act.sessionKind(key === 'kind-notes' ? 'notes' : 'handoff')
448 }
449
450 if (key.startsWith('session-')) {
451 const id = key.slice('session-'.length)
452
453 return sx.rows?.some(row => row.id === id) === true ? act.sessionPick(id) : undefined
454 }
455 }
456
457 // While a polish runs the settings and the working row are gone.
458 if (view.isRunning) {
459 return key === 'cancel' ? act.stop() : undefined
460 }
461
462 if (key === 'setup') {
463 return isBand ? undefined : act.setup()
464 }
465
466 // The band's way to read the polish in full.
467 if (key === 'panel') {
468 return isBand && view.preview !== null ? act.panel() : undefined
469 }
470
471 // The settings the pane has once opened, and the band always has.
472 const hasSettings = isBand || view.isSetupShown
473
474 if (hasSettings) {
475 if (key === 'auto') {
476 return act.auto()
477 }
478
479 if (key === 'trail') {
480 return act.trail()
481 }
482
483 if (key === 'target' || key === 'polisher' || (isBand && key === 'effort')) {
484 return act.menu(key)
485 }
486
487 if (view.menu === 'target' && key.startsWith('target-')) {
488 return act.target(key.slice('target-'.length))
489 }
490
491 // The band has the guide under the list of the session models.
492 if (key === 'guide' && (!isBand || view.menu === 'target')) {
493 return act.guide()
494 }
495
496 // The pane has the efforts always in view, as segments; the band has them
497 // in a list of their own, which a pick folds.
498 if (key.startsWith('effort-') && (!isBand || view.menu === 'effort')) {
499 act.effort(key.slice('effort-'.length))
500
501 return isBand ? act.done() : undefined
502 }
503
504 // A model picked folds its list.
505 if (view.menu === 'polisher' && key.startsWith('model-')) {
506 const name = key.slice('model-'.length)
507
508 if (view.models.includes(name)) {
509 act.model(name)
510
511 return act.done()
512 }
513 }
514 }
515
516 if (view.preview === null) {
517 return key === 'polish'
518 ? act.polish()
519 : key === 'restore'
520 ? act.undo()
521 : undefined
522 }
523
524 switch (key) {
525 case 'apply':
526 return act.apply()
527 case 'refresh':
528 return act.retry()
529 case 'discard':
530 return act.keep()
531 case 'older':
532 return act.step(-1)
533 case 'newer':
534 return act.step(1)
535 case 'original-toggle':
536 return isBand ? undefined : act.original()
537 default:
538 return undefined
539 }
540}
541
542/** A click a catcher took over one of the controls, posted by key. */
543export async function onControl(
544 $: EngineInterface,
545 e: { requestId: string; module: string; data: unknown },
546 options: PluginOptions,
547): Promise<void> {
548 const key = e.module.endsWith('hit.tsx') ? pressOf(e.data) : undefined
549
550 if (key !== undefined) {
551 await pressed($, options, key, e.requestId !== PANE)
552 }
553}
554hooks/terminal.tsx 763 lines1// The pane as the terminal draws it, and as every surface that draws from a
2// grid of cells does (the VS Code extension, the mobile app): a settings box
3// framed in the accent, blocks of color for the button that matters, toggles
4// in words. It is made of the View core.ts reads, and its controls call the
5// Act core.ts holds; there is no state or engine call in this file.
6import type { Elements, RenderElement } from 'claude-code'
7
8import type { LogLine, Menu } from '../types'
9import { TITLE } from './core'
10import { EFFORTS, fmtClock } from './polish'
11import { agoOf } from './sessions'
12import { LOG } from './view'
13import type { Act, Layout, Marks, Phase, View } from './view'
14
15/** The elements a surface drawn from cells has. */
16type Table = Pick<Elements['terminal'], 'Box' | 'Button' | 'Text'>
17
18const LOG_ROWS = 8
19
20// Theme keys, so the pane follows the person's theme.
21const C = {
22 main: 'claude',
23 polished: 'suggestion',
24 ok: 'success',
25 warn: 'error',
26 dim: 'inactive',
27 faint: 'subtle',
28 // The words on an accent block.
29 onMain: 'inverseText',
30} as const
31
32// OpenAI's brand green, for a pane polishing a prompt a GPT model will read.
33const GPT_GREEN = '#10A37F'
34
35// The key of each button, by the button's own key. A button drawn as a block
36// of color shows the key it has, so it has one only while the keys are listed.
37const HOTKEYS: Record<string, string> = {
38 polish: 'p',
39 apply: 'y',
40 refresh: 'r',
41 discard: 'x',
42 restore: 'u',
43 older: 'b',
44 newer: 'n',
45 cancel: 'c',
46 auto: 'a',
47 trail: 'e',
48 target: 't',
49 polisher: 'm',
50 log: 'l',
51 keys: 'k',
52}
53
54const KEYS = [
55 ['p', 'Prompt Polish'],
56 ['y', 'Apply Polish'],
57 ['r', 'Retry Polish'],
58 ['x', 'Keep Original'],
59 ['u', 'Undo Apply'],
60 ['b', 'Older Version'],
61 ['n', 'Newer Version'],
62 ['c', 'Stop'],
63 ['a', 'AUTO'],
64 ['e', 'TRAIL'],
65 ['t', 'Session Model'],
66 ['m', 'Polish Model'],
67 ['1-9', 'Pick from an open list'],
68 ['l', 'History'],
69 ['k', 'Keys'],
70 ['Tab', 'Next button'],
71 ['Enter', 'Press'],
72] as const
73
74export const terminalPane = (
75 { Box, Button, Text }: Table,
76 view: View,
77 act: Act,
78 layout: Layout,
79 marks: Marks,
80): RenderElement => {
81 const { isKeysShown } = view
82 const preview = view.preview
83 const draft = view.draft
84 const lines = view.lines
85 const isRunning = view.isRunning
86 const isGpt = view.isGpt
87 const open = view.menu
88 // The pane wears the colors of the family the prompt is for: Claude's
89 // from the theme, or one green on every box for a GPT model.
90 const P = isGpt
91 ? { main: GPT_GREEN, polished: GPT_GREEN, box: GPT_GREEN, rest: GPT_GREEN }
92 : { main: C.main, polished: C.polished, box: C.faint, rest: C.dim }
93 const W = Math.max(40, layout.columns)
94 const picked = { polishModel: view.model, effort: view.effort }
95 const offered = view.models
96 const made = { length: view.versions }
97 const shownAt = view.version
98 const isOn = view.isOn
99
100 // A pick list of the pane's own: every row a Button, so a click picks as
101 // Enter under the focus does. A bracketed Button keeps its key and draws
102 // none: the keys are listed under the Keys toggle, for who wants them.
103 // The button that matters now is a block of the pane's accent with its
104 // words inside, as the buttons of charmbracelet/lipgloss and gum are; the
105 // rest are their words alone, a space each side, with no block behind. A click presses it, and Tab then Enter;
106 // its key shows before it, and works, only while the keys are listed.
107 const chip = (
108 key: string,
109 label: string,
110 isMain: boolean,
111 onPress: () => void,
112 isFirst = false,
113 ) => (
114 <Button
115 key={key}
116 plain
117 {...(isKeysShown && HOTKEYS[key] !== undefined
118 ? { hotkey: HOTKEYS[key] }
119 : {})}
120 {...(isFirst ? ({ autoFocus: true } as const) : {})}
121 onPress={onPress}
122 >
123 {isMain ? (
124 <Text backgroundColor={P.main} color={C.onMain} bold>
125 {` ${label} `}
126 </Text>
127 ) : (
128 <Text>{` ${label} `}</Text>
129 )}
130 </Button>
131 )
132
133 // A pick list of the pane's own, as gum's choose draws one: a row to an
134 // option, the one in use behind a cursor and before a tick. Every row is
135 // a Button, so a click picks as Enter under the focus does.
136 type Pick = 'target' | 'model' | 'effort'
137
138 // The rows alone. `from` is how many rows the frame holds before these,
139 // so the digits of two lists in one frame run on rather than clash.
140 const pickRows = (
141 kind: Pick,
142 rows: readonly { value: string; label: string }[],
143 current: string,
144 from = 0,
145 ) =>
146 rows.map((row, i) => (
147 <Button
148 key={`${kind}-${row.value}`}
149 plain
150 {...(isKeysShown && from + i < 9
151 ? { hotkey: String(from + i + 1) }
152 : {})}
153 onPress={() => act[kind](row.value)}
154 >
155 {row.value === current ? (
156 <Text color={P.main} bold>{`> ${row.label} ✓`}</Text>
157 ) : (
158 <Text>{` ${row.label}`}</Text>
159 )}
160 </Button>
161 ))
162
163 const optionsOf = (
164 kind: Pick,
165 rows: readonly { value: string; label: string }[],
166 current: string,
167 ) => (
168 <Box
169 key={`${kind}-list`}
170 flexDirection="column"
171 borderStyle="round"
172 borderColor={P.box}
173 borderDimColor={isGpt}
174 paddingX={1}
175 >
176 {pickRows(kind, rows, current)}
177 </Box>
178 )
179
180 const mark = (kind: Menu) => (open === kind ? '▴' : '▾')
181 const plain = (values: readonly string[]) =>
182 values.map(value => ({ value, label: value }))
183
184 // What Enter does under each setting of AUTO, said alike; up only for a
185 // few seconds after a switch, in a frame right under the line the switch
186 // is on, as an open pick list is.
187 const hint = view.hint
188
189 // What the prompt is for: the switch, and the model that will read it.
190 const pickers = (
191 <Box flexDirection="column">
192 <Box columnGap={2} flexWrap="wrap">
193 {chip('auto', `AUTO ${isOn ? 'ON' : 'OFF'}`, isOn, act.auto)}
194 {chip(
195 'trail',
196 `TRAIL ${view.isTrailing ? 'ON' : 'OFF'}`,
197 view.isTrailing,
198 act.trail,
199 )}
200 {chip(
201 'target',
202 `Session Model : ${view.targetLabel} ${mark('target')}`,
203 false,
204 () => act.menu('target'),
205 )}
206 </Box>
207 {hint !== null && (
208 <Box
209 key="hint"
210 borderStyle="round"
211 borderColor={P.box}
212 borderDimColor={isGpt}
213 paddingX={1}
214 >
215 <Text color={P.main} wrap="wrap">
216 {hint}
217 </Text>
218 </Box>
219 )}
220 {open === 'target' && optionsOf('target', view.targets, view.choice)}
221 </Box>
222 )
223
224 // How hard, as a stepped slider: a track with a tick to a level and the
225 // levels named under their ticks. The ticks up to the level in use are
226 // lit, and its own is the knob. A click on a tick or on a name moves the
227 // knob there; so does Enter under the focus, and a name's digit while the
228 // keys are listed.
229 const STEP = 8
230 const at = EFFORTS.indexOf(picked.effort)
231 // Each name is centered under its tick. The track starts far enough in
232 // for the first name's left half, and a name starts half its length left
233 // of its tick; the room between two names is plain space, not button.
234 const INSET = Math.floor((EFFORTS[0]?.length ?? 0) / 2)
235 const nameStarts = EFFORTS.map(
236 (level, i) => INSET + i * STEP - Math.floor(level.length / 2),
237 )
238 const slider = (
239 <Box key="effort-slider" flexDirection="column">
240 <Box key="effort-track">
241 <Text>{' '.repeat(INSET)}</Text>
242 {EFFORTS.map((level, i) => {
243 const isLast = i === EFFORTS.length - 1
244
245 // The tick alone is the button, so the focus and the pointer
246 // light the tick and never the line; the line is one plain color.
247 return (
248 <Box>
249 <Button
250 key={`effort-tick-${level}`}
251 plain
252 onPress={() => act.effort(level)}
253 >
254 <Text color={i <= at ? P.main : C.faint} bold={i === at}>
255 {i < at ? '•' : i === at ? '●' : '○'}
256 </Text>
257 </Button>
258 {!isLast && <Text color={C.faint}>{'─'.repeat(STEP - 1)}</Text>}
259 </Box>
260 )
261 })}
262 </Box>
263 <Box key="effort-names">
264 {EFFORTS.map((level, i) => {
265 const before = EFFORTS[i - 1]
266 const gap =
267 (nameStarts[i] ?? 0) -
268 (before === undefined ? 0 : (nameStarts[i - 1] ?? 0) + before.length)
269
270 return (
271 <Box>
272 <Text>{' '.repeat(Math.max(0, gap))}</Text>
273 <Button
274 key={`effort-${level}`}
275 plain
276 {...(isKeysShown && offered.length + i < 9
277 ? { hotkey: String(offered.length + i + 1) }
278 : {})}
279 onPress={() => act.effort(level)}
280 >
281 {i === at ? (
282 <Text color={P.main} bold>
283 {level}
284 </Text>
285 ) : (
286 <Text dimColor>{level}</Text>
287 )}
288 </Button>
289 </Box>
290 )
291 })}
292 </Box>
293 </Box>
294 )
295
296 // Who polishes, and how hard: one button on the settings box's second
297 // line, saying both. Its list is one frame as wide as the box holding the
298 // models and the effort slider side by side, and it stays up after a pick,
299 // so both can be set; `done`, under it at the right, folds it, as the button does.
300 const tuning = (
301 <Box key="tuning" flexDirection="column">
302 <Box columnGap={2} flexWrap="wrap">
303 {chip(
304 'polisher',
305 `Polish Model : ${picked.polishModel} (${picked.effort}) ${mark('polisher')}`,
306 false,
307 () => act.menu('polisher'),
308 )}
309 </Box>
310 {open === 'polisher' && (
311 <Box
312 key="polisher-list"
313 flexDirection="column"
314 borderStyle="round"
315 borderColor={P.box}
316 borderDimColor={isGpt}
317 paddingX={1}
318 >
319 {/* The models at the frame's left end and the slider at its
320 right. Too narrow for both, the slider goes under the models,
321 a line left empty between them. */}
322 <Box
323 key="polisher-body"
324 justifyContent="space-between"
325 columnGap={2}
326 rowGap={1}
327 flexWrap="wrap"
328 >
329 <Box key="model-list" flexDirection="column">
330 <Text dimColor>Polish Model</Text>
331 {pickRows('model', plain(offered), picked.polishModel)}
332 </Box>
333 <Box key="effort-list" flexDirection="column">
334 <Text dimColor>Effort</Text>
335 {slider}
336 </Box>
337 </Box>
338 </Box>
339 )}
340 {/* `done`: under the list's frame and inside the settings box, at
341 the right end, as Stop is under the loading mark's. */}
342 {open === 'polisher' && (
343 <Box key="polisher-foot" justifyContent="flex-end">
344 {chip('polisher-done', 'done', false, act.done)}
345 </Box>
346 )}
347 </Box>
348 )
349
350 // The loading mark: up for as long as a polish runs, whoever began it,
351 // at the foot of the settings box, in place of the settings' buttons, in
352 // a frame of its own. Its bar is as long as that frame's inside: the
353 // pane's width less the frame, and less the settings box where it has one.
354 const loaderW = Math.max(
355 8,
356 W - 4 - (!layout.isDocked && preview === null ? 0 : 4),
357 )
358 const loader = isRunning ? (
359 <Box
360 key="loader"
361 flexDirection="column"
362 borderStyle="round"
363 borderColor={P.box}
364 borderDimColor={isGpt}
365 paddingX={1}
366 >
367 <Box columnGap={1}>
368 {marks.spinner !== undefined ? (
369 marks.spinner(view.since, view.now, P.main)
370 ) : (
371 <Text color={P.main} bold>
372 ●
373 </Text>
374 )}
375 <Text color={P.main} bold>
376 Polishing prompt
377 </Text>
378 <Text dimColor wrap="truncate">
379 {`${picked.polishModel} · effort ${picked.effort}`}
380 </Text>
381 </Box>
382 {marks.bar?.(loaderW, P.main, C.faint)}
383 </Box>
384 ) : null
385
386 // Stop: under the mark's frame and inside the settings box, the box's
387 // last line, at its right end.
388 const stopRow = isRunning ? (
389 <Box key="loader-foot" justifyContent="flex-end">
390 {chip('cancel', 'Stop', false, act.stop, true)}
391 </Box>
392 ) : null
393
394 const phase: {
395 kind: Phase
396 glyph: string
397 text: string
398 color: string
399 } = isRunning
400 ? { kind: 'busy', glyph: '●', text: 'Polishing', color: P.main }
401 : preview !== null || view.isAnswering
402 ? { kind: 'review', glyph: '◆', text: 'Review', color: P.polished }
403 : { kind: 'idle', glyph: '●', text: 'Ready', color: C.dim }
404
405 // The state: a mark that moves where the surface can animate, still elsewhere.
406 const phaseColor = phase.kind === 'idle' ? C.ok : phase.color
407 const status = (
408 <Box columnGap={1} flexShrink={0}>
409 {marks.pulse !== undefined ? (
410 marks.pulse(phase.kind, phaseColor)
411 ) : (
412 <Text color={phaseColor}>{phase.glyph}</Text>
413 )}
414 <Text color={phase.color} bold={phase.kind !== 'idle'}>
415 {phase.text}
416 </Text>
417 </Box>
418 )
419
420 const actions = view.isAnswering ? (
421 <Box key="waiting" columnGap={1} flexWrap="wrap">
422 <Text color={P.polished} bold>
423 Waiting for your answer
424 </Text>
425 <Text dimColor>
426 Pick Apply Polish, Keep Original or Retry Polish in the question.
427 </Text>
428 </Box>
429 ) : preview !== null ? (
430 <Box columnGap={2} flexWrap="wrap">
431 {chip('apply', 'Apply Polish', true, act.apply, true)}
432 {chip('refresh', 'Retry Polish', false, act.retry)}
433 {chip('discard', 'Keep Original', false, act.keep)}
434 </Box>
435 ) : (
436 <Box key="primary" columnGap={2} flexWrap="wrap">
437 {chip('polish', 'Prompt Polish', true, act.polish)}
438 {draft !== null && chip('restore', 'Undo Apply', false, act.undo)}
439 </Box>
440 )
441
442 // The versions a retry has made of the draft on preview, paged through as
443 // assistant-ui's BranchPicker pages a message's branches: the one before,
444 // which of how many is on show, the one after. With one version there is
445 // nothing to page, and at either end the arrow is no button.
446 const arrow = (key: 'older' | 'newer', glyph: string, by: -1 | 1) =>
447 shownAt + by < 0 || shownAt + by >= made.length ? (
448 <Text color={C.faint}>{` ${glyph} `}</Text>
449 ) : (
450 chip(key, glyph, false, () => act.step(by))
451 )
452 const pager =
453 preview !== null && made.length > 1 ? (
454 <Box key="versions" flexShrink={0}>
455 {arrow('older', '‹', -1)}
456 <Text dimColor>{`${shownAt + 1} / ${made.length}`}</Text>
457 {arrow('newer', '›', 1)}
458 </Box>
459 ) : null
460
461 // The pane's working row: what to do now, and at its far end the pager of
462 // what a retry made. While a polish runs there is only Stop to do, which
463 // stands with the loading mark, so the row is gone, pager and all.
464 const actionRow = (
465 <Box
466 key="action-row"
467 paddingX={1}
468 columnGap={2}
469 flexWrap="wrap"
470 alignItems="flex-start"
471 {...(pager === null ? {} : ({ justifyContent: 'space-between' } as const))}
472 width={W}
473 >
474 {actions}
475 {pager}
476 </Box>
477 )
478
479 const rowOf = (line: LogLine) => (
480 <Box>
481 <Box width={9} flexShrink={0}>
482 <Text color={C.faint}>{fmtClock(line.at)}</Text>
483 </Box>
484 <Box width={10} flexShrink={0}>
485 <Text color={LOG[line.kind].color} bold wrap="truncate">
486 {LOG[line.kind].label}
487 </Text>
488 </Box>
489 <Text wrap="truncate">{line.text}</Text>
490 </Box>
491 )
492
493 // The foot, a line clear of the working panels: the keys' toggle, and under it
494 // the record's, which is the pane's last row. Each list opens right above
495 // its own toggle, so the two rows keep their order and the last its place.
496 const latest = lines.at(-1)
497 // The toggle's mark: up while folded, the way its list opens; down while open.
498 const fold = (isOpen: boolean) => (isOpen ? '▾' : '▴')
499
500 const logPanel = (
501 <Box key="foot" flexDirection="column" marginTop={1} width={W}>
502 {isKeysShown && (
503 <Box
504 key="keys-list"
505 flexDirection="column"
506 borderStyle="round"
507 borderColor={P.box}
508 borderDimColor={isGpt}
509 paddingX={1}
510 width={W}
511 >
512 <Text color={C.faint} wrap="wrap">
513 Keys work while this list is open. Click the pane or press ctrl+x
514 tab first.
515 </Text>
516 <Box columnGap={3} flexWrap="wrap">
517 {KEYS.map(([key, what]) => (
518 <Text>
519 <Text color={P.main} bold>
520 {key}
521 </Text>
522 <Text dimColor>{` ${what}`}</Text>
523 </Text>
524 ))}
525 </Box>
526 </Box>
527 )}
528 <Box key="keys-row" paddingX={1}>
529 {chip('keys', `Keys ${fold(isKeysShown)}`, false, act.keys)}
530 </Box>
531 {view.isLogShown && (
532 <Box
533 key="log-list"
534 flexDirection="column"
535 borderStyle="round"
536 borderColor={P.box}
537 borderDimColor={isGpt}
538 paddingX={1}
539 width={W}
540 >
541 {lines.length === 0 && <Text color={C.faint}>No history yet</Text>}
542 {lines.slice(-LOG_ROWS).map(rowOf)}
543 </Box>
544 )}
545 <Box key="log-row" paddingX={1} columnGap={1}>
546 <Box flexShrink={0}>
547 {chip(
548 'log',
549 `${lines.length === 0 ? 'History' : `History ${lines.length}`} ${fold(view.isLogShown)}`,
550 false,
551 act.log,
552 )}
553 </Box>
554 {!view.isLogShown && latest !== undefined && (
555 <Text dimColor wrap="truncate">
556 {`${fmtClock(latest.at)} ${LOG[latest.kind].label} · ${latest.text}`}
557 </Text>
558 )}
559 </Box>
560 </Box>
561 )
562
563 const clickNote = layout.isFullscreen
564 ? null
565 : 'No mouse clicks on this screen (fullscreen only)'
566
567 // Inline above the prompt with nothing to review, the pane is a summary.
568 if (!layout.isDocked && preview === null) {
569 return (
570 <Box key="pane" flexDirection="column" width={W}>
571 <Box columnGap={1}>
572 <Text color={P.main} bold>
573 {TITLE}
574 </Text>
575 {status}
576 </Box>
577 {!isRunning && actionRow}
578 {isRunning ? loader : pickers}
579 {stopRow}
580 {!isRunning && tuning}
581 {clickNote !== null && (
582 <Text color={C.faint} wrap="truncate">
583 {clickNote}
584 </Text>
585 )}
586 {logPanel}
587 </Box>
588 )
589 }
590
591 const settingsPanel = (
592 <Box
593 key="settings"
594 flexDirection="column"
595 borderStyle="round"
596 borderColor={P.main}
597 paddingX={1}
598 width={W}
599 >
600 <Box justifyContent="space-between">
601 <Button key="guide" plain onPress={act.guide}>
602 <Text color={P.main} bold>
603 Reference : {view.guide} Guide
604 </Text>
605 </Button>
606 {status}
607 </Box>
608 {view.isGuideShown && (
609 <Box
610 key="about"
611 borderStyle="round"
612 borderColor={P.box}
613 borderDimColor={isGpt}
614 paddingX={1}
615 >
616 <Text dimColor wrap="wrap">
617 {view.about}
618 </Text>
619 </Box>
620 )}
621 <Box key="divider">
622 <Text color={P.box} dimColor={isGpt}>
623 {'─'.repeat(Math.max(1, W - 4))}
624 </Text>
625 </Box>
626 {isRunning ? loader : pickers}
627 {stopRow}
628 {!isRunning && tuning}
629 </Box>
630 )
631
632 const textPanel = (
633 key: string,
634 title: string,
635 text: string,
636 color: string,
637 border: string,
638 isDim: boolean,
639 w: number,
640 ) => (
641 <Box
642 key={key}
643 flexDirection="column"
644 borderStyle="round"
645 borderColor={border}
646 borderDimColor={isDim}
647 paddingX={1}
648 width={w}
649 >
650 <Box justifyContent="space-between">
651 <Text color={color} bold>
652 {title}
653 </Text>
654 <Text dimColor>{`${text.trim().length} chars`}</Text>
655 </Box>
656 <Text dimColor={isDim} wrap="wrap">
657 {text.trim()}
658 </Text>
659 </Box>
660 )
661
662 const isWide = W >= 110
663 const half = Math.floor((W - 2) / 2)
664 const review =
665 preview === null ? null : isWide ? (
666 <Box key="review" columnGap={2}>
667 {textPanel('original', 'Original Prompt', draft ?? '', C.dim, P.rest, true, half)}
668 {textPanel('polished', 'Polished Prompt', preview, P.polished, P.polished, false, half)}
669 </Box>
670 ) : (
671 <Box key="review" flexDirection="column">
672 {textPanel('original', 'Original Prompt', draft ?? '', C.dim, P.rest, true, W)}
673 {textPanel('polished', 'Polished Prompt', preview, P.polished, P.polished, false, W)}
674 </Box>
675 )
676
677 // The earlier sessions of this project, to pick one up from: a chip that
678 // opens the list, the last day or up to a week, and a session opened for a
679 // closer look with a chip to hand it over to this one.
680 const sx = view.sessions
681 const sessionsPanel = isRunning || preview !== null || view.isAnswering ? null : (
682 <Box key="sessions-panel" flexDirection="column" paddingX={1} width={W}>
683 <Box key="sessions-head">
684 {chip('sessions', `Earlier sessions ${sx.isOpen ? '▴' : '▾'}`, false, act.sessions)}
685 </Box>
686 {sx.isOpen && (
687 <Box key="sessions-body" flexDirection="column">
688 <Box key="range-row" columnGap={1}>
689 {chip('range-day', 'Last 24 hours', sx.range === 'day', () => act.sessionsRange('day'))}
690 {chip('range-week', 'Up to 7 days', sx.range === 'week', () => act.sessionsRange('week'))}
691 </Box>
692 {sx.isLoading && <Text color={C.faint}>Reading the sessions…</Text>}
693 {!sx.isLoading && sx.rows !== null && sx.rows.length === 0 && (
694 <Text color={C.faint} wrap="wrap">
695 {sx.range === 'day'
696 ? 'No earlier session in the last 24 hours. Try up to 7 days.'
697 : 'No earlier session in the last 7 days.'}
698 </Text>
699 )}
700 {!sx.isLoading &&
701 (sx.rows ?? []).map(row => {
702 const isPicked = sx.picked === row.id
703 const isDone = sx.done.some(entry => entry.id === row.id)
704
705 return (
706 <Box key={`session-${row.id}-item`} flexDirection="column">
707 <Button key={`session-${row.id}`} plain onPress={() => act.sessionPick(row.id)}>
708 <Text>{`${isPicked ? '▾' : '▸'} ${agoOf(sx.now, row.at)} · ${row.title}${row.files > 0 ? ` (${row.files} ${row.files === 1 ? 'file' : 'files'})` : ''}${row.hasHandoff ? ' [handoff]' : ''}${isDone ? ' ✓' : ''}`}</Text>
709 </Button>
710 {isPicked && (
711 <Box key={`session-${row.id}-detail`} flexDirection="column" paddingLeft={2}>
712 {row.last !== '' && (
713 <Text color={C.faint} wrap="wrap">{`Last prompt: ${row.last}`}</Text>
714 )}
715 <Box columnGap={1}>
716 {row.hasHandoff &&
717 chip('kind-notes', 'Notes', sx.kind === 'notes', () => act.sessionKind('notes'))}
718 {row.hasHandoff &&
719 chip('kind-handoff', 'Handoff document', sx.kind === 'handoff', () =>
720 act.sessionKind('handoff'),
721 )}
722 {chip(
723 'session-take',
724 isDone ? 'Hand over again' : 'Hand over to this session',
725 true,
726 act.sessionTake,
727 )}
728 </Box>
729 </Box>
730 )}
731 </Box>
732 )
733 })}
734 </Box>
735 )}
736 </Box>
737 )
738
739 // Docked, the pane is as tall as its room, so the foot sits on its last row.
740 return (
741 <Box
742 key="pane"
743 flexDirection="column"
744 width={W}
745 {...(layout.isDocked ? { minHeight: Math.max(1, layout.bodyRows) } : {})}
746 >
747 {settingsPanel}
748 {review}
749 {!isRunning && actionRow}
750 {clickNote !== null && (
751 <Box paddingX={1}>
752 <Text color={C.faint} wrap="truncate">
753 {clickNote}
754 </Text>
755 </Box>
756 )}
757 {sessionsPanel}
758 {layout.isDocked && <Box key="spacer" flexGrow={1} />}
759 {logPanel}
760 </Box>
761 )
762}
763hooks/view.ts 142 lines1// What a frontend is given. The pane has one body of logic (core.ts) and a
2// frontend for each kind of surface (terminal.tsx, desktop.tsx); the logic
3// reads the state into a View, the frontend draws it, and the frontend's
4// controls call back into Act. A frontend never reads state or calls the
5// engine: what it shows is the View, and what it does is Act.
6import type { ModelEffort, RenderElement } from 'claude-code'
7
8import type { LogKind, LogLine, Menu, SessionsState, TargetChoice } from '../types'
9
10export type Phase = 'idle' | 'review' | 'busy'
11
12/** What each row of the record is called, and the theme color of its mark. */
13export const LOG: Record<LogKind, { label: string; color: string }> = {
14 polish: { label: 'Polished', color: 'suggestion' },
15 refresh: { label: 'Retried', color: 'suggestion' },
16 apply: { label: 'Applied', color: 'success' },
17 keep: { label: 'Kept', color: 'inactive' },
18 fail: { label: 'Failed', color: 'error' },
19}
20
21/** The earlier sessions as the pane draws them: the list, the time it is told against, and the sessions handed over to this one. */
22export type SessionsView = Omit<SessionsState, 'done'> & {
23 /** The sessions handed over to the one now open, each with the title it was listed by. */
24 done: { id: string; title: string }[]
25 now: number
26}
27
28/** The pane as the state stands: plain data, drawn the same way each time. */
29export type View = {
30 phase: Phase
31 /** AUTO: Enter polishes first and asks you before sending. */
32 isOn: boolean
33 /** TRAIL: the person's own switch for keeping the session trail. */
34 isTrailing: boolean
35 /** The earlier sessions of this project, to pick one up from. */
36 sessions: SessionsView
37 isRunning: boolean
38 /** Whether a prompt is held in auto mode and a question about its polish waits for an answer. */
39 isAnswering: boolean
40 /** Whether the prompt is for a GPT model, which the pane wears the green of. */
41 isGpt: boolean
42 /** The guide in use, and the line that says what it is. */
43 guide: string
44 about: string
45 isGuideShown: boolean
46 /** The model the prompt is for: the pick, its words, and every choice. */
47 choice: TargetChoice
48 targetLabel: string
49 targets: readonly { value: string; label: string }[]
50 /** Who polishes: the models offered, the one picked, and how hard. */
51 models: readonly string[]
52 model: string
53 effort: ModelEffort
54 /** The pick list that is open. */
55 menu: Menu | null
56 /** The draft on preview, the polish of it on show, and which of how many. */
57 draft: string | null
58 preview: string | null
59 version: number
60 versions: number
61 /** The record, oldest first. */
62 lines: readonly LogLine[]
63 isLogShown: boolean
64 isKeysShown: boolean
65 /** The desktop folds its settings into a line, and the original into a toggle. */
66 isSetupShown: boolean
67 isOriginalShown: boolean
68 /** What Enter does under AUTO, for the few seconds after a switch; else null. */
69 hint: string | null
70 /** When the polish now running began, and the time as it was read. */
71 since: number
72 now: number
73 /** Whether a surface that can draw a catcher over a control is to go without. */
74 isPlain: boolean
75}
76
77/** What each control of the pane does. */
78export type Act = {
79 guide: () => void
80 auto: () => void
81 trail: () => void
82 /** Opens or folds the list of earlier sessions. */
83 sessions: () => void
84 /** Opens the pane beside the conversation with the list of earlier sessions open. */
85 sessionsPanel: () => void
86 /** The list over the last day, or up to a week. */
87 sessionsRange: (range: 'day' | 'week') => void
88 /** Opens a session of the list for a closer look, or folds it. */
89 sessionPick: (id: string) => void
90 /** What a hand-over gives: notes made of the session, or its handoff document. */
91 sessionKind: (kind: 'notes' | 'handoff') => void
92 /** Hands the opened session over to this one. */
93 sessionTake: () => void
94 menu: (which: Menu) => void
95 done: () => void
96 target: (value: string) => void
97 model: (value: string) => void
98 effort: (value: string) => void
99 polish: () => void
100 apply: () => void
101 retry: () => void
102 keep: () => void
103 undo: () => void
104 stop: () => void
105 step: (by: -1 | 1) => void
106 log: () => void
107 keys: () => void
108 setup: () => void
109 original: () => void
110 /** Opens the pane beside the conversation, to read a polish in full. */
111 panel: () => void
112 /** The same, with the record open. */
113 history: () => void
114 /** Opens the desktop's band, or minimizes it to the chip in the prompt's footer. */
115 band: (isOpen: boolean) => void
116}
117
118/** The room the surface gives the pane. */
119export type Layout = {
120 columns: number
121 isDocked: boolean
122 bodyRows: number
123 isFullscreen: boolean
124}
125
126/**
127 * The surface modules the pane may draw, each there only where the surface
128 * runs one. A `module` is written in the hooks module (register.tsx), which is
129 * where the engine reads the paths of the modules from, so a frontend is
130 * handed the elements and draws them where it wants them.
131 */
132export type Marks = {
133 /** The state's mark: moves with the phase. */
134 pulse?: (phase: Phase, color: string) => RenderElement
135 /** The loading mark and the time a polish has run. */
136 spinner?: (since: number, now: number, color: string) => RenderElement
137 /** The loading line, `width` cells long. */
138 bar?: (width: number, color: string, dim: string) => RenderElement
139 /** A catcher over the control keyed `key`, `rows` rows of it at most. */
140 catcher?: (key: string, rows: number) => RenderElement
141}
142hooks/pulse.tsx 49 lines1// The pane's state mark, moving on the surface's own frame clock so the pane
2// need not redraw for it: at rest a dot, which does not move; the MiniDot
3// spinner of charmbracelet/bubbles while a polish runs; its Points while a
4// preview waits for an answer. A mark that does not move has no clock.
5import type { ClientModule } from 'claude-code'
6
7type Props = { kind: 'idle' | 'review' | 'busy'; color: string }
8type Ref = { ticks: number; stop: (() => void) | null }
9type State = { ref: Ref }
10
11const TICK_MS = 100
12
13// `hold` is how many ticks each frame stays up.
14const MARKS = {
15 idle: { hold: 1, frames: ['●'] },
16 review: { hold: 2, frames: ['∙∙∙', '●∙∙', '∙●∙', '∙∙●'] },
17 busy: { hold: 1, frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] },
18} as const
19
20const Pulse: ClientModule<Props, State> = (props, surface) => {
21 const { Text } = surface.elements
22 const ref = surface.state?.ref ?? { ticks: 0, stop: null }
23 const mark = MARKS[props.kind]
24 const isMoving = mark.frames.length > 1
25
26 // The clock starts when the mark moves, once, and stops when it comes to rest.
27 if (isMoving && ref.stop === null) {
28 ref.stop = surface.every(TICK_MS, () => {
29 ref.ticks += 1
30 surface.setState({ ref })
31 })
32 surface.setState({ ref })
33 } else if (!isMoving && ref.stop !== null) {
34 ref.stop()
35 ref.stop = null
36 ref.ticks = 0
37 }
38
39 const frame = Math.floor(ref.ticks / mark.hold) % mark.frames.length
40
41 return (
42 <Text color={props.color} bold>
43 {mark.frames[frame]}
44 </Text>
45 )
46}
47
48export default Pulse
49hooks/spinner.tsx 47 lines1// The pane's loading mark: a spinner and the time a polish has run, ticking on
2// the surface's own frame clock so the pane need not redraw for it.
3// `since` and `now` come from the hooks module's $.clock; between redraws it
4// adds its own ticks.
5import type { ClientModule } from 'claude-code'
6
7type Props = { since: number; now: number; color: string }
8type Ref = { base: number; ticks: number; lastNow: number }
9type State = { ref: Ref }
10
11const FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
12const TICK_MS = 100
13
14const fmt = (ms: number): string => {
15 const seconds = Math.max(0, Math.floor(ms / 1000))
16
17 return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`
18}
19
20const Spinner: ClientModule<Props, State> = (props, surface) => {
21 const { Text } = surface.elements
22 const ref = surface.state?.ref ?? { base: 0, ticks: 0, lastNow: -1 }
23
24 if (props.now !== ref.lastNow) {
25 // A fresh reading from the hooks module: restart the local count from it.
26 ref.lastNow = props.now
27 ref.base = props.now - props.since
28 ref.ticks = 0
29 }
30
31 if (surface.state === undefined) {
32 surface.setState({ ref })
33 surface.every(TICK_MS, () => {
34 ref.ticks += 1
35 surface.setState({ ref })
36 })
37 }
38
39 return (
40 <Text color={props.color} bold>
41 {`${FRAMES[ref.ticks % FRAMES.length]} ${fmt(ref.base + ref.ticks * TICK_MS)}`}
42 </Text>
43 )
44}
45
46export default Spinner
47hooks/bar.tsx 45 lines1// The loading line: a short lit stretch that runs along a dotted track and comes
2// round again for as long as a polish runs, on the surface's own frame clock.
3// It says "working", never "this far along": a model call reports no progress,
4// so nothing here fills up or counts down.
5import type { ClientModule } from 'claude-code'
6
7type Props = { width: number; color: string; dim: string }
8type Ref = { ticks: number }
9type State = { ref: Ref }
10
11const TICK_MS = 45
12const LIT = 6
13// Dots, not a line: the rule under the pane's heading is a line, and the two
14// stand one above the other.
15const TRACK = '·'
16
17const Bar: ClientModule<Props, State> = (props, surface) => {
18 const { Text } = surface.elements
19 const ref = surface.state?.ref ?? { ticks: 0 }
20
21 if (surface.state === undefined) {
22 surface.setState({ ref })
23 surface.every(TICK_MS, () => {
24 ref.ticks += 1
25 surface.setState({ ref })
26 })
27 }
28
29 const width = Math.max(LIT + 2, Math.floor(props.width))
30 // The stretch enters at the left edge, leaves at the right, and enters again.
31 const head = (ref.ticks % (width + LIT)) - LIT
32 const from = Math.max(0, head)
33 const to = Math.min(width, head + LIT)
34
35 return (
36 <Text>
37 <Text color={props.dim}>{TRACK.repeat(from)}</Text>
38 <Text color={props.color}>{'━'.repeat(Math.max(0, to - from))}</Text>
39 <Text color={props.dim}>{TRACK.repeat(width - to)}</Text>
40 </Text>
41 )
42}
43
44export default Bar
45hooks/hit.tsx 70 lines1// A catcher laid over one of the pane's controls, where a surface draws the
2// pane from a tree it was sent: it takes a click anywhere on the control (its
3// icon, its chevron, the room around its words) and posts the control's key.
4//
5// It is here for the clicks a button there loses. Such a surface names a
6// button by a handle the engine gives out afresh on every redraw, and the
7// click that gives the pane the keyboard redraws it: by the time that click
8// is let go, its button's handle is gone, and the press with it. A post names
9// the catcher by its key, which a redraw leaves alone.
10import type { ClientModule } from 'claude-code'
11
12// `press` is the key of the control under the catcher; `rows` is how many
13// rows of it there are at most, past which a click let go is no click.
14type Props = { press: string; rows?: number }
15type Ref = { isOver: boolean; isDown: boolean }
16type State = { ref: Ref }
17
18// A gray that stands on a dark page and on a light one, a sixth as strong
19// under the pointer and a quarter under a press.
20const OVER = '#8C8C8C2B'
21const DOWN = '#8C8C8C40'
22
23const Hit: ClientModule<Props, State> = (props, surface) => {
24 const { Box } = surface.elements
25 const ref = surface.state?.ref ?? { isOver: false, isDown: false }
26 const rows = Math.max(1, Math.floor(props.rows ?? 2))
27
28 // Set on every call, so the listener posts the key the control has now.
29 surface.onPointer(event => {
30 if (event.type === 'enter' || event.type === 'leave') {
31 ref.isOver = event.type === 'enter'
32 } else if (event.type === 'down' && event.button === 'left') {
33 ref.isDown = true
34 } else if (event.type === 'up') {
35 // Let go off the control, the click is taken back, as a button's is.
36 // Before the region is laid out its width is not known, and not asked.
37 const isOn =
38 event.y >= 0 &&
39 event.y < rows &&
40 event.x >= 0 &&
41 (surface.columns === 0 || event.x < surface.columns)
42
43 if (ref.isDown && isOn && event.button === 'left') {
44 surface.post({ press: props.press })
45 }
46
47 ref.isDown = false
48 } else {
49 return
50 }
51
52 surface.setState({ ref })
53 })
54
55 // Taller than any control: the room it is given cuts it to the control's own.
56 return (
57 <Box
58 width="100%"
59 height={rows + 1}
60 {...(ref.isDown
61 ? { backgroundColor: DOWN }
62 : ref.isOver
63 ? { backgroundColor: OVER }
64 : {})}
65 />
66 )
67}
68
69export default Hit
70hooks/guides.ts 142 lines1import type { Target, TargetChoice } from '../types'
2
3/**
4 * `about` is what the pane says of the guide when asked; `rules` is what the
5 * polisher reads; `sources` are the published pages the rules were written from.
6 */
7export type Guide = {
8 label: string
9 about: string
10 sources?: readonly string[]
11 rules: string
12}
13
14export const CHOICES: readonly TargetChoice[] = [
15 'auto',
16 'opus-5.5',
17 'sonnet-5.5',
18 'gpt-6-astra',
19 'gpt-5.6',
20]
21
22export const GUIDES: Record<Target, Guide> = {
23 'opus-5.5': {
24 label: 'Opus 5.5',
25 about:
26 'Prompting tips for Claude Opus 5.5. Give the whole task with a clear finish line, say which stops you want, and drop "think step by step" phrases.',
27 sources: [
28 'https://claude.dev/blog/getting-the-most-out-of-opus-5-5/',
29 'https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5',
30 ],
31 rules: `대상 모델: Claude Opus 5.5
32
33보강할 것
34- 작업 전체를 한 메시지에 담고, 끝나는 지점("테스트 통과", "모든 엔드포인트 마이그레이션 완료" 같은 완료 기준)을 명시한다.
35- 여러 단계에 걸친 작업이면 멈춤 규칙을 적는다: 사용자 입력이 필요 없는 단계는 계속 진행하고 상태 보고는 다음 작업과 같은 메시지에 쓴다. 사용자 없이는 진행할 수 없을 때와 파괴적 작업(데이터 삭제, force-push, 저장소 밖 변경) 직전에만 멈춘다.
36- 대규모 코드베이스 감사·마이그레이션·리뷰면 서브에이전트에 나눠 맡기고, 각 결과의 근거를 확인한 뒤 받아들이라고 적는다. 결과를 한 표로 모아야 하면 표의 열을 지정한다.
37- 길게 이어질 작업이면 작업 목록을 파일(예: TASKS.md 체크리스트)로 관리하고, 끝낸 항목은 체크하고 새로 발견한 항목은 추가하라고 적는다.
38- 코드 리뷰 요청이면 머지를 막을 문제만 나열하고, 문제마다 파일과 줄, 틀린 이유, 실패를 재현하는 방법을 적으라고 한다.
39- 조사·분석 요청이면 확인하지 못한 것을 표시하고 어디를 찾아봤는지 적으라고 한다.
40- 긴 문서·계획·발표자료 검토 요청이면 무엇을 찾을지(서로 어긋나는 숫자, 날짜, 이름)를 지정하고, 문제마다 원문을 인용하고 위치를 적으라고 한다.
41- 파일 산출물(스프레드시트, 문서)을 원하면 개요가 아니라 완성된 파일을 요청하고, 행과 열 구성을 적는다.
42- 디자인 요청이면 피할 스타일을 구체적인 패턴으로 나열한다. 초안에 단서가 없으면 크림색·미색 배경, 제목의 이탤릭 강조 단어, "01/02/03" 번호 섹션 라벨, 모노스페이스 라벨, 알약 모양 버튼을 예로 든다.
43- 이메일, 문서, 스프레드시트처럼 여러 앱에 걸친 작업인데 어디를 볼지 정해져 있지 않으면, 손대기 전에 관련 자료를 먼저 폭넓게 찾아 읽으라고 적는다.
44- 진행 보고를 원하는 초안이면 시점을 정한다: 시작 전 한 줄 계획, 끝난 뒤 짧은 요약.
45
46지우거나 바꿀 것
47- "think carefully", "think step by step", "신중하게 생각해" 같은 문구는 지운다. 간단한 질문에 빠른 답을 원하는 초안이면 "바로 답해줘"로 바꾼다.
48- 내부 추론 과정을 답변에 그대로 쓰라는 요청은 "이 접근을 고른 이유를 세 문장으로 설명해줘"처럼 짧은 설명이나 수행한 작업 요약을 묻는 요청으로 바꾼다.
49- "뻔한 AI 느낌 피해줘" 같은 막연한 지시는 구체적인 패턴 나열로 바꾼다.`,
50 },
51 'sonnet-5.5': {
52 label: 'Sonnet 5.5',
53 about:
54 'Prompting tips for Claude Sonnet 5.5. Give a clear spec and a way to check it, ask for real checks before "done", and drop workarounds made for older models.',
55 sources: [
56 'https://claude.dev/blog/building-with-claude-sonnet-5-5/',
57 'https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-sonnet-5-5',
58 ],
59 rules: `대상 모델: Claude Sonnet 5.5
60
61보강할 것
62- 작업의 스펙과 결과를 확인할 방법을 명시한다. 이 모델은 범위가 분명하고 결과를 검증할 수 있는 작업에 가장 잘 맞는다.
63- 여러 부분으로 된 코딩 작업이면 요청한 것이 모두 끝날 때까지 계속 진행하고, 사용자 없이 진행할 수 없거나 위험한 단계 직전에만 멈춰 물으라고 적는다.
64- 코딩 작업이면 실행·빌드·타입체크할 수 있는 변경은 그 변경을 실제로 거치는 검증(프로젝트의 테스트, 타입체커, 빌드, 또는 바꾼 명령 자체)을 돌린 뒤에 완료를 보고하라고 적는다. 검증을 돌릴 수 없으면 무엇을 왜 돌리지 못했는지 말하라고 적는다.
65- 초안이 변경 범위를 한정하면 범위를 명시한다: 요청한 작업이 끝나고 검증되면 멈추고 보고하며, 요청하지 않은 기능·테스트·파일·문서·리팩터링은 추가하지 말고 필요해 보이면 끝에 언급만 하라고 적는다. 추가 리뷰나 리뷰용 서브에이전트도 요청이 없으면 시작하지 말라고 적는다.
66- 아이디어·선택지·계획만 원하는 열린 요청이면 그것만 주고 멈추며, 진행하라는 말이 있기 전에는 결과물(발표자료, 보고서, 코드)을 만들거나 바꾸지 말라고 명시한다.
67- 허용 여부, 요건, 요금처럼 바뀌었을 수 있는 사실이나 보고서·비교 같은 조사 작업이면, 기억에 의존하지 말고 검색으로 최신 출처를 확인하라고 적는다.
68- 진행 보고를 원하는 초안이면 시점을 정한다: 첫 도구 호출 전 한 줄 계획, 끝난 뒤 짧은 요약.
69
70지우거나 바꿀 것
71- "do not be lazy", 거절을 피하려는 유도 문구, 도구 호출 재시도 지시 같은 이전 모델용 우회 문구는 지운다.
72- "덜 생각해", "빨리 답해", "생각하지 마" 같은 생각량 조절 문구는 지운다. 프롬프트의 이런 지시는 생각량을 안정적으로 줄이지 못한다.
73- "꼭 필요할 때만 도구 사용", "도구 호출 최소화" 같은 도구 사용 억제 문구는 지운다.
74- "결과는 마지막 답변에 한꺼번에 보고" 같은 중간 보고 억제 문구는 지운다.
75- 내부 추론 과정을 답변에 그대로 쓰라는 요청은 짧은 설명이나 수행한 작업 요약을 묻는 요청으로 바꾼다.`,
76 },
77 'gpt-6-astra': {
78 label: 'GPT-6 Astra',
79 about:
80 'Prompting tips for OpenAI GPT-6 Astra. Say what "done" means up front, give direct orders instead of "can you", and cut step-by-step recipes.',
81 rules: `대상 모델: OpenAI GPT-6 Astra
82
83보강할 것
84- 완료 기준을 미리 정한다. 실행 확인, 결과 점검, 실패 수정까지가 작업이면 처음부터 요청에 넣는다.
85- "~해줄 수 있어?", "도와줘"는 직접 지시문으로 바꾸고, 가능 여부만 답하거나 계획만 제안하고 멈추지 말라고 적는다.
86- 배포, PR 머지, 게시처럼 승인이 필요한 일이 있으면 필요한 작업을 먼저 끝내고 승인을 마지막 단계로 두라고 적는다. 되돌릴 수 있는 작업과 읽기 전용 작업은 허락 없이 진행하게 한다.
87- skill이나 AGENTS.md가 걸릴 만한 작업이면 사용자 지시가 우선한다고 적고, 지침 때문에 멈추면 원인이 된 파일과 문장을 인용하라고 적는다.
88- 나눠서 처리할 수 있는 큰 작업이면 서브에이전트에 위임할 시점을 지정한다.
89- 글 결과물을 요청하면서 산문이 필요하면 산문으로 쓰라고 지정한다.
90
91지우거나 바꿀 것
92- "테스트 꼭 돌려라" 같은 지시는 지운다. 작은 변경이면 테스트 범위를 좁히라고 적는다.
93- "모든 편집 전에 문서를 전부 읽어" 같은 지시는 상황별로 어떤 문서를 볼지만 남긴다.
94- "먼저 물어봐" 같은 이전 모델용 경계 문구는 지운다.
95- 첫 구현 후 리뷰를 위해 멈추라는 요구는 지운다.
96- 단계별 레시피처럼 지나치게 상세한 지침은 목표와 제약만 남긴다.`,
97 },
98 'gpt-5.6': {
99 label: 'GPT-5.6',
100 about:
101 'Prompting tips for OpenAI GPT-5.6. Keep it short, say what needs approval, and remove repeated or clashing rules.',
102 rules: `대상 모델: OpenAI GPT-5.6
103
104보강할 것
105- 간결하게 만든다: 반복되는 지시와 불필요한 예시를 지우고, 각 지시는 한 번만 쓴다.
106- 자율성과 승인 경계를 정의한다: 변경 요청이면 범위 내 로컬 변경과 비파괴 검증은 묻지 않고 진행하고, 외부 쓰기·파괴적 작업·구매·범위 확장만 확인을 받게 한다. 답변·설명·리뷰·계획 요청이면 결과만 보고하게 한다.
107- 짧은 답을 원하면 무엇을 남길지 지정한다: 결론, 근거, 주요 주의사항, 다음 행동.
108- 톤 요청은 "친근하게" 같은 라벨 대신 구체적인 행동(답을 얼마나 직접 말할지, 문제를 언제 인정할지)으로 적는다.
109
110지우거나 바꿀 것
111- "Be concise" 같은 포괄적인 간결성 지시는 지운다.
112- "먼저 물어봐", "변경하지 마", "승인 기다려"가 여러 번 나오면 한 번만 남기고, 안전한 작업에 걸린 것은 지운다.
113- 서로 충돌하는 규칙은 하나로 정리한다.
114- "더 깊게 생각해"나 여러 후보 답안을 만들라는 요청은 지운다.`,
115 },
116}
117
118/**
119 * The guide a session's model reads best: by the id `/model` shows, Opus 5.5
120 * for one that names none of the four.
121 */
122export const targetOf = (model: string): Target => {
123 const id = model.toLowerCase()
124
125 if (id.includes('sonnet')) {
126 return 'sonnet-5.5'
127 }
128
129 if (id.includes('gpt-6') || id.includes('astra')) {
130 return 'gpt-6-astra'
131 }
132
133 if (id.includes('gpt-5')) {
134 return 'gpt-5.6'
135 }
136
137 return 'opus-5.5'
138}
139
140export const isChoice = (value: unknown): value is TargetChoice =>
141 CHOICES.some(choice => choice === value)
142