SLOPSHOPPER

quick-replies

전역과 로컬(저장소별) 프리셋 문구를 입력창 위에 버튼으로 표시합니다. $4처럼 입력하면 해당 문구로 바뀌고, 문구를 클릭하면 바로 보냅니다. /스킬도 실행할 수 있으며, $e로 편집 화면을 열거나 $0으로 프리셋을 한 줄로 접을 수 있습니다

bandspinnertoastpromptmodelprocess
★ 1v0.14.2MITupdated 2026-10-21oobg/claude-code-mods/mods/quick-replies
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · quick-replies
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM 전역 $e: 편집 $0: 접기 $1: 지금 진행상황 $2: 맞아 그렇게 진행해 ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
전역 $e: 편집 $0: 접기 $1: 지금 진행상황 $2: 맞아 그렇게 진행해
README

<img alt="claude-code-mods 로고" src="./docs/images/logo.png" width="160">

<h1 align="center">claude-code-mods</h1>

<a href="./LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/license-MIT-111111?style=flat-square"></a> <a href="https://claude.com/claude-code"><img alt="Claude Code 2.1.303" src="https://img.shields.io/badge/Claude%20Code-2.1.303-111111?style=flat-square"></a> <a href="#설치"><img alt="marketplace oobg" src="https://img.shields.io/badge/marketplace-oobg-111111?style=flat-square"></a> <img alt="6 mods" src="https://img.shields.io/badge/mods-6-D97757?style=flat-square"> <a href="https://github.com/oobg/claude-code-mods/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/oobg/claude-code-mods?style=flat-square&color=111111"></a>

<a href="#주요-기능"><b>주요 기능</b></a> &nbsp;|&nbsp; <a href="#설치"><b>설치</b></a> &nbsp;|&nbsp; <a href="#모드-목록"><b>모드 목록</b></a> &nbsp;|&nbsp; <a href="#상세-문서"><b>상세 문서</b></a> &nbsp;|&nbsp; <a href="https://oobg.github.io/claude-code-mods/"><b>문서 사이트</b></a>

claude-code-mods는 Claude Code의 입력창과 도구 결과에 기능을 추가하는 모드 6개를 모은 저장소입니다. 입력창 위에서는 다음 요청을 제안하고 자주 쓰는 문구 프리셋을 표시하며, 입력창 아래에서는 세션 상태를 보여 줍니다. Finder에서 복사한 파일을 붙여넣으면 파일 이름을 @경로 멘션으로 바꾸고, Cmd+Z로 입력 내용을 되돌릴 수 있습니다. 넓은 터미널에서는 Edit와 Write 결과의 diff를 좌우로 비교할 수 있습니다. 새 버전이 설치되면 알리고, Orca 탭에서는 기존 대화를 이어서 다시 엽니다. 필요한 모드만 골라 설치할 수 있습니다. relaunch의 자동 다시 열기에는 Orca가 필요합니다.

주요 기능

<table class="cards"> <tr> <td width="50%" valign="top"> <a href="./docs/next-prompts.md"><picture> <img alt="next-prompts: 턴이 끝나면 다음에 보낼 만한 요청이 하나씩 나타난다" src="./docs/images/showcase/suggest-light.gif" width="100%"> <sub>턴이 끝나면 다음에 보낼 만한 요청을 최대 3개 제안합니다. <code>$1</code>을 입력하고 스페이스를 누르거나 번호를 클릭하면 문구가 입력창에 들어가고, 문구를 클릭하면 바로 보냅니다</sub> </td> <td width="50%" valign="top"> <a href="./docs/quick-replies.md"><picture> <img alt="quick-replies: 입력창에 $1을 치고 스페이스를 누르면 $1이 1번 프리셋 문구로 바뀐다" src="./docs/images/showcase/preset-light.gif" width="100%"> <sub>자주 쓰는 문구를 전역 또는 저장소별 프리셋으로 저장합니다. 입력창에 <code>$4</code>를 치고 스페이스를 누르면 해당 문구로 바뀝니다</sub> </td> </tr> <tr> <td width="50%" valign="top"> <a href="./docs/dashboard.md"><picture> <img alt="dashboard: 컨텍스트 게이지가 차면서 색이 바뀐다" src="./docs/images/showcase/gauge-light.gif" width="100%"> <sub>모델, 컨텍스트, 사용 한도, 브랜치를 입력창 아래 두 줄에 표시합니다. 게이지가 찰수록 색이 노란색, 주황색, 빨간색 순으로 바뀝니다</sub> </td> <td width="50%" valign="top"> <a href="./docs/key-assist.md"><picture> <img alt="key-assist: 붙여넣은 파일 이름이 @경로로 바뀐다" src="./docs/images/showcase/paste-light.gif" width="100%"> <sub>Finder에서 복사한 파일을 붙여넣으면 파일 이름이 <code>@경로</code>로 바뀝니다. Cmd+Z로 입력 내용을 되돌릴 수 있습니다</sub> </td> </tr> <tr> <td colspan="2" valign="top"> <a href="./docs/split-diff.md"><picture> <img alt="split-diff: 터미널 폭이 120칸 이상이면 좌우 diff, 미만이면 원래 세로 diff로 전환된다" src="./docs/images/showcase/split-diff-light.gif" width="100%"> <sub>터미널 폭이 120칸 이상이면 Edit와 Write 결과의 diff에서 원래 내용은 왼쪽에, 바뀐 내용은 오른쪽에 표시합니다. 바뀐 단어는 더 밝은 색으로 강조합니다</sub> </td> </tr> <tr> <td colspan="2" valign="top"> <a href="./docs/relaunch.md"><picture> <img alt="relaunch: 업데이트 알림의 다시 열기를 누르면 같은 탭에서 새 버전으로 같은 대화가 열린다" src="./docs/images/showcase/relaunch-light.gif" width="49%"> <img alt="relaunch: 입력창에 /relaunch를 치고 Enter를 누르면 같은 탭에서 새 버전으로 같은 대화가 열린다" src="./docs/images/showcase/relaunch-type-light.gif" width="49%"> <sub>새 버전이 설치되면 입력창 위에 알립니다. Orca 탭에서 <code>다시 열기</code>를 누르거나(왼쪽) <code>/relaunch</code>를 입력하면(오른쪽) Claude Code를 다시 시작하고 기존 대화를 이어서 엽니다</sub> </td> </tr> </table>

특징

  • $번호로 문구를 불러옵니다. 다음 제안과 프리셋에 각각 번호가 붙습니다. 입력창에 $2를 치고 스페이스를 누르면 2번 문구가 그 자리에 들어가고, 이어서 쓸 수 있게 뒤에 스페이스가 하나 붙습니다. 스페이스 없이 바로 Enter를 눌러도 문구로 바꿔 보냅니다. $12처럼 두 자리 번호도 쓸 수 있습니다.
  • 프리셋도 입력창에서 편집합니다. 편집 화면에서 프리셋을 추가하거나 수정할 때는 입력창에 내용을 쓰고 Enter를 누르면 됩니다.
  • 상태 표시줄 대신 입력창 아래에 대시보드를 표시합니다. 컨텍스트 사용량, 5시간과 7일 한도, Fable 한도, 모델, 브랜치를 두 줄로 확인할 수 있습니다.
  • 파일을 경로 멘션으로 붙여넣습니다. Finder에서 복사한 파일을 붙여넣으면 파일 이름 대신 @경로 멘션이 입력됩니다.
  • 넓은 터미널에서는 diff를 좌우로 나눠 표시합니다. 원래 줄과 바뀐 줄이 같은 높이에 나란히 표시됩니다.
  • 업데이트 후 기존 대화를 이어서 엽니다. 새 버전이 설치되면 입력창 위에 알립니다. Orca 탭에서는 /relaunch로 다시 시작해 기존 대화를 이어서 엽니다.
  • 따로 설치할 프로그램이나 직접 고칠 설정 파일이 없습니다. 마켓플레이스에서 필요한 모드만 골라 설치합니다.

설치

요구 사항

  • Claude Code 2.1.296 이상이 필요합니다. 기존 모드는 2.1.296~2.1.303, relaunch는 2.1.303에서 테스트했습니다. 모드 기능은 아직 공개 초기 단계라 이후 버전에서는 동작이 달라질 수 있습니다.
  • key-assist는 macOS 전용입니다. Cmd+Z를 사용하려면 Command 키 입력을 Claude Code에 전달할 수 있는 터미널이 필요합니다. Orca, Ghostty, kitty, WezTerm처럼 Kitty 키보드 프로토콜을 지원하는 터미널이 해당합니다.
  • relaunch가 자동으로 다시 열려면 Orca 터미널 탭과 orca 명령이 필요합니다. 업데이트 알림은 다른 터미널에서도 나타납니다.

마켓플레이스에서 설치

이 저장소가 oobg 마켓플레이스입니다. 먼저 Claude Code 입력창에서 마켓플레이스를 등록합니다.

/plugin marketplace add oobg/claude-code-mods

그다음 필요한 모드만 골라 설치합니다.

/plugin install next-prompts@oobg
/plugin install quick-replies@oobg
/plugin install dashboard@oobg
/plugin install key-assist@oobg
/plugin install split-diff@oobg
/plugin install relaunch@oobg

설치한 모드는 Claude Code를 다시 시작하거나 /reload-plugins를 실행하면 적용됩니다. 설치 여부는 /plugin 화면에서 확인하거나 터미널에서 claude plugin list를 실행해 확인할 수 있습니다.

Claude Code를 시작하면 quick-replies의 기본 프리셋과 dashboard가 바로 표시됩니다. next-prompts의 제안은 첫 턴이 끝난 뒤에 나타납니다.

모드 목록

모드기능위치
next-prompts턴이 끝나면 다음에 보낼 만한 요청을 최대 3개 제안합니다입력창 위
quick-replies자주 쓰는 문구를 전역 프리셋이나 저장소별 프리셋에 저장합니다입력창 위
dashboard모델, 컨텍스트, 사용 한도, 브랜치를 두 줄로 표시합니다입력창 아래
key-assist붙여넣은 파일 이름을 @경로로 바꾸고, Cmd+Z로 입력한 내용을 되돌립니다입력창
split-diff넓은 터미널에서 Edit와 Write 결과의 diff를 좌우로 나눠 표시합니다도구 결과
relaunch새 버전 설치를 알리고, Orca 탭에서 기존 대화를 이어서 다시 엽니다입력창 위, /relaunch

$번호로 문구 입력하기

next-prompts와 quick-replies를 함께 쓰면 입력창 위에 표시되는 두 목록의 번호가 이어집니다. 다음 제안은 $1부터, 프리셋은 그다음 번호부터 시작합니다.

<table class="cards"> <tr> <td width="50%" valign="top"> <a href="./docs/quick-replies.md"><picture> <img alt="입력창에 $2를 치고 스페이스를 누르면 $2가 2번 문구로 바뀐다" src="./docs/images/showcase/substitute-light.gif" width="100%"> <sub>입력창에 <code>$2</code>를 치고 스페이스를 누르면 <code>$2</code>가 2번 문구로 바뀝니다. 문장 중간에서도 사용할 수 있습니다</sub> </td> <td width="50%" valign="top"> <a href="./docs/quick-replies.md"><picture> <img alt="번호를 클릭하면 입력창 내용이 그 문구로 바뀐다" src="./docs/images/showcase/pick-light.gif" width="100%"> <sub>번호(<code>$2:</code>)를 클릭하면 입력창의 기존 내용을 모두 2번 문구로 바꿉니다</sub> </td> </tr> <tr> <td width="50%" valign="top"> <a href="./docs/next-prompts.md"><picture> <img alt="문구를 클릭하면 그 문구만 바로 보내진다" src="./docs/images/showcase/send-light.gif" width="100%"> <sub>문구를 클릭하면 해당 문구만 바로 보냅니다. 입력창에 적어 둔 내용은 그대로 남습니다</sub> </td> <td width="50%" valign="top"> <a href="./docs/quick-replies.md"><picture> <img alt="$e를 입력하면 프리셋 편집 화면이 열린다" src="./docs/images/showcase/editor-light.gif" width="100%"> <sub>입력창에 <code>$e</code>를 입력하면 프리셋 편집 화면이 열립니다</sub> </td> </tr> <tr> <td width="50%" valign="top"> <a href="./docs/quick-replies.md"><picture> <img alt="$0을 입력하면 프리셋을 한 줄로 접고 다시 입력하면 펼친다" src="./docs/images/showcase/fold-light.gif" width="100%"> <sub>입력창에 <code>$0</code>을 입력하면 프리셋을 한 줄로 접고, 다시 입력하면 펼칩니다</sub> </td> <td width="50%"></td> </tr> </table>

입력창 맨 앞이나 공백 뒤에 $와 번호를 치고 스페이스를 누르면 그 자리에서 문구로 바뀝니다. 스페이스 없이 Enter를 누르면 입력창에는 보이지 않고 보내는 내용만 바뀝니다. 입력창에서 바뀐 내용은 ctrl+_로 되돌릴 수 있습니다.

업데이트와 삭제

먼저 마켓플레이스 목록을 갱신합니다.

/plugin marketplace update oobg

그다음 /plugin 화면에서 설치한 모드를 업데이트하거나, 터미널에서 claude plugin update <모드>@oobg를 실행합니다. 업데이트한 모드는 Claude Code를 다시 시작하면 적용됩니다.

모드를 삭제하려면 다음 명령을 실행합니다.

/plugin uninstall next-prompts@oobg
/plugin uninstall quick-replies@oobg
/plugin uninstall dashboard@oobg
/plugin uninstall key-assist@oobg
/plugin uninstall split-diff@oobg
/plugin uninstall relaunch@oobg

[!NOTE] key-assist를 삭제해도 키 설정에 추가된 cmd+z 항목은 남습니다. 필요하지 않으면 ~/.claude/keybindings.json에서 직접 지웁니다.

문제 해결

모드별 자세한 해결 방법은 각 상세 문서의 "문제 해결" 절에서 확인할 수 있습니다.

상세 문서

각 모드의 상세 문서는 문서 사이트에서도 볼 수 있습니다.

문서내용
next-prompts제안을 넣고 보내고 닫는 방법, quick-replies와 함께 쓰기, 알아 둘 점
quick-replies전역 프리셋과 로컬 프리셋, 불러오기, 스킬과 슬래시 명령, 접기, 편집 화면
dashboard표시하는 항목, 모양 바꾸기, 색 바꾸기, 상태줄과 함께 쓸 때
key-assist파일 붙여넣기, Cmd+Z로 되돌리기, 알아 둘 점
split-diff좌우로 나뉘는 조건, 실제 화면, 알아 둘 점
relaunch다시 열기 버튼과 /relaunch, 알아 둘 점

라이선스

Copyright (c) 2026 oobg

이 프로젝트는 MIT 라이선스에 따라 배포됩니다.

Source 4 files
hooks/register.tsx 688 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Deleted, EditInput, Mode, Reply, Scope } from '../types'
5import { exclusiveBand, expandNumbers, expandRanges, numberLabel, rangeText, typedAfterDollar, typedNumber, typedRange, withBandSection } from './band'
6import { MAX_TITLE_TOKENS, TITLE_SYSTEM, needsTitle, parseTitle, shortTitle, titlePrompt } from './title'
7
8export const DEFAULT_REPLIES: readonly string[] = ['지금 진행상황', '맞아 그렇게 진행해']
9
10// 띠 안의 순서. next-prompts의 다음 제안(10) 아래에 온다.
11const ORDER = 20
12// 스킬, 슬래시 명령 프리셋의 명령 부분 색. 버튼 번호와 입력창의 /명령에 Claude Code가 쓰는 테마 색과 같다.
13const ACCENT = 'suggestion'
14
15const repo = atom({ plugin: 'quick-replies', key: 'repo' } as const, null)
16const globalReplies = atom({ plugin: 'quick-replies', key: 'globalReplies' } as const, null)
17const projectReplies = atom({ plugin: 'quick-replies', key: 'projectReplies' } as const, null)
18const mode = atom({ plugin: 'quick-replies', key: 'mode' } as const, { kind: 'view' } as Mode)
19const compact = atom({ plugin: 'quick-replies', key: 'compact' } as const, null)
20
21// next-prompts가 띄운 다음 제안. 프리셋 번호는 그 개수 다음부터 매긴다. next-prompts가 없으면 비어 있다.
22// 이 모드의 상태가 아니라서 계약에 적지 않고, 모양도 믿지 않고 걸러 읽는다.
23const nextSuggestions = atom({ plugin: 'next-prompts', key: 'suggestions' } as never, [] as never)
24
25async function suggestionList($: EngineInterface): Promise<string[]> {
26  try {
27    const list: unknown = await read($, nextSuggestions)
28    return Array.isArray(list) ? list.filter(item => typeof item === 'string') : []
29  } catch {
30    return []
31  }
32}
33
34async function suggestionCount($: EngineInterface): Promise<number> {
35  return (await suggestionList($)).length
36}
37
38// 다음 제안과 프리셋을 띠에 보이는 번호로 찾는다. 범위(`$2-$4`)는 둘에 걸칠 수 있어 함께 찾는다.
39async function numbered($: EngineInterface): Promise<(n: number) => string | undefined> {
40  const { global, project } = await current($)
41  const texts = [...(await suggestionList($)), ...[...global, ...project].map(reply => reply.text)]
42  return n => texts[n - 1]
43}
44
45const GLOBAL_KEY = 'global'
46const COMPACT_KEY = 'compact'
47const projectKey = (root: string) => `repo:${root}`
48
49// git 저장소 안이면 그 최상위 폴더, 아니면 세션 폴더가 프로젝트 프리셋의 단위다.
50async function findRepo($: EngineInterface): Promise<string> {
51  const cwd = await $.session.cwd()
52  try {
53    const { exitCode, stdout } = await $.process.run(['git', 'rev-parse', '--show-toplevel'])
54    return exitCode === 0 && stdout.trim() !== '' ? stdout.trim() : cwd
55  } catch {
56    return cwd
57  }
58}
59
60const defaults = (): Reply[] => DEFAULT_REPLIES.map((text, i) => ({ id: `default-${i}`, text }))
61
62type Presets = { root: string; global: Reply[]; project: Reply[] }
63
64// 그리기는 상태를 쓰지 못하므로 읽기만 한다. 세션 시작 때 채운 값이 있으면 그것을, 없으면 저장소에서 바로 읽는다.
65// 전역은 한 번도 고치지 않았으면 기본 두 개, 프로젝트는 비어 있다.
66async function current($: EngineInterface): Promise<Presets> {
67  const root = (await read($, repo)) ?? (await findRepo($))
68  const global =
69    (await read($, globalReplies)) ??
70    (((await $.store.get(GLOBAL_KEY)) as Reply[] | undefined) ??
71      defaults())
72  const project = (await read($, projectReplies)) ?? (((await $.store.get(projectKey(root))) as Reply[] | undefined) ?? [])
73  return { root, global, project }
74}
75
76// 접힘도 프리셋처럼 세션 시작 때 채운 값을 먼저, 없으면 저장소에서 읽는다. 처음에는 펼쳐 둔다.
77async function isCompact($: EngineInterface): Promise<boolean> {
78  return (await read($, compact)) ?? (((await $.store.get(COMPACT_KEY)) as boolean | undefined) ?? false)
79}
80
81async function toggleCompact($: EngineInterface): Promise<void> {
82  const next = !(await isCompact($))
83  await update($, compact, () => next)
84  await $.store.set(COMPACT_KEY, next)
85}
86
87async function load($: EngineInterface): Promise<void> {
88  const { root, global, project } = await current($)
89  await update($, repo, () => root)
90  await update($, globalReplies, () => global)
91  await update($, projectReplies, () => project)
92  const folded = await isCompact($)
93  await update($, compact, () => folded)
94}
95
96// 다른 세션에서 고친 프리셋을 이 세션에 들인다. 저장소는 파일 하나라서 바뀌었다는 알림이 없으므로 주기적으로 읽어 비교한다.
97// 띠는 세션 값을 읽어 그리므로, 값이 달라질 때만 바꾸면 그때만 다시 그려진다.
98export const SYNC_MS = 5000
99
100async function sync($: EngineInterface): Promise<void> {
101  const root = await read($, repo)
102  if (root === null) {
103    return
104  }
105  const stored = {
106    global: ((await $.store.get(GLOBAL_KEY)) as Reply[] | undefined) ?? defaults(),
107    project: ((await $.store.get(projectKey(root))) as Reply[] | undefined) ?? [],
108  }
109  if (JSON.stringify(stored.global) !== JSON.stringify(await read($, globalReplies))) {
110    await update($, globalReplies, () => stored.global)
111  }
112  if (JSON.stringify(stored.project) !== JSON.stringify(await read($, projectReplies))) {
113    await update($, projectReplies, () => stored.project)
114  }
115}
116
117// 두 목록을 함께 바꾼다. 한 프리셋을 전역과 프로젝트 사이로 옮길 때 양쪽을 한 번에 저장하기 위해서다.
118async function save($: EngineInterface, change: (presets: Presets) => Presets): Promise<void> {
119  const next = change(await current($))
120  await update($, repo, () => next.root)
121  await update($, globalReplies, () => next.global)
122  await update($, projectReplies, () => next.project)
123  await $.store.set(GLOBAL_KEY, next.global)
124  await $.store.set(projectKey(next.root), next.project)
125}
126
127// "/ux-writing 문구 다듬어줘"처럼 /로 시작하는 프리셋은 슬래시 명령(스킬 포함)으로 실행한다.
128// 이름과 나머지를 나눈다. 명령이 아니면 null.
129export function parseCommand(text: string): { command: string; args: string } | null {
130  const match = /^\/([^\s/]+)(?:\s+([\s\S]*))?$/.exec(text.trim())
131  return match === null ? null : { command: match[1] ?? '', args: (match[2] ?? '').trim() }
132}
133
134// 프리셋 하나를 보낸다. 슬래시 명령은 사람이 입력한 것처럼 실행한다.
135// /로 시작하는 글은 일반 프롬프트로 보낼 수 없으므로, 없는 명령이면 알림만 띄운다.
136async function send($: EngineInterface, text: string): Promise<void> {
137  const command = parseCommand(text)
138  if (command === null) {
139    await $.prompt.submit({ text, asUser: true })
140    return
141  }
142  const known = (await $.command.list()).some(c => c.name === command.command)
143  if (!known) {
144    $.ui.toast(`/${command.command}에 해당하는 명령이나 스킬을 찾지 못했어요`)
145    return
146  }
147  await $.command.run(command)
148}
149
150const without = (list: Reply[], id: string) => list.filter(r => r.id !== id)
151const untitled = ({ title: _title, autoTitle: _auto, ...rest }: Reply): Reply => rest
152// 문구를 고치면 모델이 지은 제목은 버리고 다시 짓는다. 사람이 단 제목은 그대로 둔다.
153const renamed = (list: Reply[], id: string, text: string) =>
154  list.map(r => (r.id !== id ? r : r.autoTitle ? { ...untitled(r), text } : { ...r, text }))
155// 사람이 단 제목. 빈 제목은 제목을 지워, 모델이 다시 짓게 한다.
156const retitled = (list: Reply[], id: string, title: string) =>
157  list.map(r => (r.id !== id ? r : title === '' ? untitled(r) : { ...untitled(r), title }))
158// 모델이 지은 제목. 그사이 문구가 바뀌었거나 사람이 제목을 달았으면 버린다.
159const autoTitled = (list: Reply[], id: string, text: string, title: string) =>
160  list.map(r => (r.id === id && r.text === text && r.title === undefined ? { ...r, title, autoTitle: true as const } : r))
161
162// 지금 제목을 짓고 있는 프리셋 id와 그때의 문구. 같은 문구로 두 번 묻지 않는다.
163const titling = new Map<string, string>()
164
165// 제목이 없는 긴 프리셋에 작은 모델(haiku)로 제목을 지어 단다. 제목은 덤이라 실패하면 문구를 줄여 보인다.
166async function autoTitle($: EngineInterface, reply: Reply): Promise<void> {
167  if (!needsTitle(reply) || titling.get(reply.id) === reply.text) {
168    return
169  }
170  titling.set(reply.id, reply.text)
171  try {
172    const answer = await $.model.complete({
173      model: 'haiku',
174      system: TITLE_SYSTEM,
175      prompt: titlePrompt(reply.text),
176      maxTokens: MAX_TITLE_TOKENS,
177      effort: 'low',
178      timeoutMs: 20_000,
179    })
180    const title = answer.isAnswered ? parseTitle(answer.text) : ''
181    if (title !== '') {
182      await save($, p => ({
183        ...p,
184        global: autoTitled(p.global, reply.id, reply.text, title),
185        project: autoTitled(p.project, reply.id, reply.text, title),
186      }))
187    }
188  } catch {
189    // 제목을 못 지으면 접은 띠에 문구를 줄여 보인다.
190  } finally {
191    if (titling.get(reply.id) === reply.text) {
192      titling.delete(reply.id)
193    }
194  }
195}
196
197// 한 프리셋의 제목을 다시 살핀다. 기다리지 않는다.
198async function titleLater($: EngineInterface, id: string): Promise<void> {
199  const { global, project } = await current($)
200  const reply = [...global, ...project].find(r => r.id === id)
201  if (reply !== undefined) {
202    void autoTitle($, reply)
203  }
204}
205
206// 세션을 열 때 제목이 없는 긴 프리셋에 차례로 제목을 단다. 한 번 지은 제목은 저장되어 다시 묻지 않는다.
207async function titleAll($: EngineInterface): Promise<void> {
208  const { global, project } = await current($)
209  for (const reply of [...global, ...project]) {
210    await autoTitle($, reply)
211  }
212}
213
214// 편집 화면을 연다. 키보드는 입력창에 그대로 두고, 편집하는 동안 입력창에 치는 키를 이 모드가 가로챈다.
215// 띠로 포커스를 옮기면 모드가 입력창으로 되돌릴 방법이 없어서다.
216async function openEditor($: EngineInterface): Promise<void> {
217  await update($, mode, () => ({ kind: 'edit', selected: null, input: null }) as Mode)
218}
219
220// 문구를 쓰는 동안 입력창 글자에 칠하는 색. 입력창 테두리는 모드가 바꿀 수 없어 글자로 편집 중임을 보인다.
221const inputPaint = (text: string) => [{ start: 0, end: text.length, color: ACCENT } as const]
222
223// 입력칸을 연다. 입력창이 곧 입력칸이라, 고칠 때는 원래 글을 입력창에 채워 둔다.
224async function startInput($: EngineInterface, editing: EditInput): Promise<void> {
225  const presets = await current($)
226  const target = editing.kind === 'add' ? undefined : [...presets.global, ...presets.project].find(r => r.id === editing.id)
227  const text = editing.kind === 'rename' ? (target?.text ?? '') : editing.kind === 'title' ? (target?.title ?? '') : ''
228  await update($, mode, m => (m.kind === 'edit' ? { ...m, input: editing } : m))
229  await $.prompt.fill({ text, decorations: inputPaint(text) })
230}
231
232async function cancelInput($: EngineInterface): Promise<void> {
233  await update($, mode, m => (m.kind === 'edit' ? { ...m, input: null } : m))
234  await $.prompt.fill({ text: '' })
235}
236
237// 입력칸에서 Enter를 누르면 추가하거나 고친다. 빈 문구는 무시하고, 빈 제목은 제목을 지운다.
238// 제목이 비면 모델이 뒤에서 제목을 짓는다.
239async function submitInput($: EngineInterface, editing: EditInput, text: string): Promise<void> {
240  if (editing.kind === 'title') {
241    await save($, p => ({
242      ...p,
243      global: retitled(p.global, editing.id, text),
244      project: retitled(p.project, editing.id, text),
245    }))
246    await titleLater($, editing.id)
247  } else if (text !== '') {
248    if (editing.kind === 'add') {
249      const reply = { id: crypto.randomUUID(), text }
250      await save($, p =>
251        editing.scope === 'global' ? { ...p, global: [...p.global, reply] } : { ...p, project: [...p.project, reply] },
252      )
253      await titleLater($, reply.id)
254    } else {
255      await save($, p => ({
256        ...p,
257        global: renamed(p.global, editing.id, text),
258        project: renamed(p.project, editing.id, text),
259      }))
260      await titleLater($, editing.id)
261    }
262  }
263  await update($, mode, m => (m.kind === 'edit' ? { ...m, input: null } : m))
264}
265
266// 지우고 커서는 그 자리에 들어선 프리셋(맨 뒤였으면 앞의 것)으로 옮긴다. 지운 것은 `u`로 되살릴 수 있게 남긴다.
267async function removePreset($: EngineInterface, id: string): Promise<void> {
268  const before = ordered(await current($))
269  const at = before.findIndex(item => item.reply.id === id)
270  const target = before[at]
271  if (target === undefined) {
272    return
273  }
274  const deleted: Deleted = { reply: target.reply, scope: target.scope, index: before.filter(i => i.scope === target.scope).indexOf(target) }
275  await save($, p => ({ ...p, global: without(p.global, id), project: without(p.project, id) }))
276  const after = before.filter(item => item.reply.id !== id)
277  const next = after[Math.min(at, after.length - 1)]?.reply.id ?? null
278  await update($, mode, m => (m.kind === 'edit' ? { ...m, selected: next, deleted } : m))
279}
280
281// 마지막으로 지운 프리셋을 원래 범위의 원래 자리에 되살리고 커서를 둔다.
282async function restorePreset($: EngineInterface, deleted: Deleted): Promise<void> {
283  const put = (list: Reply[]) => [...list.slice(0, deleted.index), deleted.reply, ...list.slice(deleted.index)]
284  await save($, p => (deleted.scope === 'global' ? { ...p, global: put(p.global) } : { ...p, project: put(p.project) }))
285  await update($, mode, m => (m.kind === 'edit' ? { ...m, selected: deleted.reply.id, deleted: undefined } : m))
286}
287
288// 전역과 로컬 사이로 옮긴다. 옮긴 프리셋은 그쪽 목록 맨 뒤에 붙는다.
289async function movePreset($: EngineInterface, id: string): Promise<void> {
290  await save($, p => {
291    const inGlobal = p.global.find(r => r.id === id)
292    if (inGlobal !== undefined) {
293      return { ...p, global: without(p.global, id), project: [...p.project, inGlobal] }
294    }
295    const inProject = p.project.find(r => r.id === id)
296    return inProject === undefined ? p : { ...p, project: without(p.project, id), global: [...p.global, inProject] }
297  })
298}
299
300// 같은 범위 안에서 한 칸 위(-1)나 아래(+1)로 옮긴다.
301function shifted(list: Reply[], id: string, by: number): Reply[] {
302  const from = list.findIndex(r => r.id === id)
303  const to = from + by
304  if (from < 0 || to < 0 || to >= list.length) {
305    return list
306  }
307  const next = [...list]
308  const [moved] = next.splice(from, 1)
309  next.splice(to, 0, moved as Reply)
310  return next
311}
312
313async function reorder($: EngineInterface, id: string, by: number): Promise<void> {
314  await save($, p => ({ ...p, global: shifted(p.global, id, by), project: shifted(p.project, id, by) }))
315}
316
317// 전역 다음 로컬 순서로 늘어놓은 목록. 편집 화면의 번호와 커서는 이 순서를 따른다.
318function ordered(presets: Presets): { reply: Reply; scope: Scope }[] {
319  return [
320    ...presets.global.map(reply => ({ reply, scope: 'global' as Scope })),
321    ...presets.project.map(reply => ({ reply, scope: 'project' as Scope })),
322  ]
323}
324
325// 두 번 쳐야 하는 키. 첫 글자는 `pending`에 두었다가 같은 글자가 오면 실행한다.
326const SEQUENCES = ['dd', 'gg']
327
328// 편집 화면에서 고르는 중일 때 입력창에 친 글자 하나를 vim처럼 동작으로 바꾼다. 띠의 버튼도 같은 글자로 이 함수를 부른다.
329//   j/k 커서 아래/위, gg/G 처음/끝, 1~9 그 번호로, J/K 프리셋을 아래/위로 옮기기
330//   i 문구 수정, t 제목, dd 삭제, u 되살리기, m 전역↔로컬, o 커서가 있는 범위에 추가, q 완료
331async function editorKey($: EngineInterface, key: string): Promise<void> {
332  const shown = await read($, mode)
333  if (shown.kind !== 'edit') {
334    return
335  }
336  const pending = shown.pending ?? ''
337  if (pending !== '') {
338    await update($, mode, m => (m.kind === 'edit' ? { ...m, pending: undefined } : m))
339  }
340  const typed = SEQUENCES.includes(pending + key) ? pending + key : key
341  if (SEQUENCES.some(seq => seq[0] === typed && seq.length === 2)) {
342    await update($, mode, m => (m.kind === 'edit' ? { ...m, pending: typed } : m))
343    return
344  }
345  const all = ordered(await current($))
346  const select = async (index: number) => {
347    const picked = all[Math.max(0, Math.min(index, all.length - 1))]
348    if (picked !== undefined) {
349      await update($, mode, m => (m.kind === 'edit' ? { ...m, selected: picked.reply.id, input: null } : m))
350    }
351  }
352  if (/^[1-9]$/.test(typed)) {
353    if (Number(typed) <= all.length) {
354      await select(Number(typed) - 1)
355    }
356    return
357  }
358  const at = all.findIndex(item => item.reply.id === shown.selected)
359  const selected = all[at]
360  const actions: Record<string, () => Promise<void>> = {
361    j: () => select(at < 0 ? 0 : at + 1),
362    k: () => select(at < 0 ? all.length - 1 : at - 1),
363    gg: () => select(0),
364    G: () => select(all.length - 1),
365    o: () => startInput($, { kind: 'add', scope: selected?.scope ?? 'global' }),
366    q: async () => {
367      await update($, mode, () => ({ kind: 'view' }) as Mode)
368    },
369    ...(shown.deleted === undefined ? {} : { u: () => restorePreset($, shown.deleted as Deleted) }),
370    ...(selected === undefined
371      ? {}
372      : {
373          i: () => startInput($, { kind: 'rename', id: selected.reply.id }),
374          t: () => startInput($, { kind: 'title', id: selected.reply.id }),
375          dd: () => removePreset($, selected.reply.id),
376          m: () => movePreset($, selected.reply.id),
377          K: () => reorder($, selected.reply.id, -1),
378          J: () => reorder($, selected.reply.id, 1),
379        }),
380  }
381  await actions[typed]?.()
382}
383
384const SAVED: Record<EditInput['kind'], string> = { add: '프리셋을 추가했어요', rename: '문구를 고쳤어요', title: '제목을 바꿨어요' }
385
386export const register: Register = on => {
387  on('session.start', async ($, e, next) => {
388    const result = await next(e)
389    await load($)
390    void titleAll($)
391    $.clock.every(SYNC_MS, () => void sync($))
392    return result
393  })
394
395  // 입력창에 `$5 `, `$12 `처럼 번호 뒤에 스페이스를 치면 그 자리를 그 번호의 프리셋 문구로 바꾼다. 번호는 띠에 보이는 것과 같게 셈한다.
396  // `$e`는 편집 화면을 열고 `$0`은 프리셋을 접거나 편다. 이때 친 `$e`, `$0`은 입력창에 남기지 않는다.
397  on('prompt.edit', async ($, e, next) => {
398    const shown = await read($, mode)
399    if (shown.kind === 'edit') {
400      // 고르는 중에는 입력창에 친 글자를 하나도 넣지 않고 편집 동작으로만 쓴다.
401      if (shown.input === null) {
402        if (e.key !== undefined && e.inputText.length === 1) {
403          void editorKey($, e.inputText)
404        }
405        return next({ ...e, start: e.cursor, end: e.cursor, inputText: '' })
406      }
407      // 문구를 쓰는 중에는 입력창이 입력칸이다. `$q`를 치면 취소한다.
408      if (typedAfterDollar(e) === 'q') {
409        const box = await next({ ...e, start: e.start - 1, inputText: '' })
410        void cancelInput($)
411        return box
412      }
413      const box = await next(e)
414      return { ...box, decorations: inputPaint(box.text) }
415    }
416    const typed = typedAfterDollar(e)
417    if ((typed === 'e' || typed === '0') && (await read($, mode)).kind === 'view') {
418      const box = await next({ ...e, start: e.start - 1, inputText: '' })
419      void (typed === 'e' ? openEditor($) : toggleCompact($))
420      return box
421    }
422    const range = typedRange(e)
423    if (range !== undefined && (await read($, mode)).kind === 'view') {
424      const text = rangeText(range, await numbered($))
425      if (text !== undefined) {
426        return next({ ...e, start: range.start, inputText: text })
427      }
428    }
429    const typedN = typedNumber(e)
430    if (typedN !== undefined && (await read($, mode)).kind === 'view') {
431      const presets = await current($)
432      const reply = [...presets.global, ...presets.project][typedN.n - 1 - (await suggestionCount($))]
433      if (reply !== undefined) {
434        return next({ ...e, start: typedN.start, inputText: `${reply.text} ` })
435      }
436    }
437    return next(e)
438  })
439
440  // 편집하는 동안 Enter는 Claude에게 보내지 않는다. 문구를 쓰는 중이면 그 글을 저장하고, 결과를 알림 대신 보내기를 막은 이유로 보인다.
441  on('prompt.submit', async ($, e, next) => {
442    const shown = await read($, mode)
443    if (e.origin.kind !== 'composer') {
444      return next(e)
445    }
446    // 스페이스 없이 `$번호`에서 바로 Enter를 눌러도 그 번호의 프리셋으로 바꿔 보낸다. 다음 제안의 번호는 next-prompts가 바꾼다.
447    // `$번호-$번호` 범위는 다음 제안에 걸쳐도 여기서 함께 바꾼다.
448    // 글 전체가 `/명령` 프리셋 하나면 클릭한 것처럼 명령으로 실행한다.
449    if (shown.kind === 'view') {
450      const { global, project } = await current($)
451      const presets = [...global, ...project]
452      const offset = await suggestionCount($)
453      const lookup = (n: number) => (n > offset ? presets[n - 1 - offset]?.text : undefined)
454      const whole = /^\$([1-9][0-9]*)$/.exec(e.text.trim())
455      const single = whole === null ? undefined : lookup(Number(whole[1]))
456      const command = single === undefined ? null : parseCommand(single)
457      if (single !== undefined && command !== null) {
458        void send($, single)
459        void $.prompt.fill({ text: '' })
460        return { drop: `/${command.command} 프리셋을 실행해요` }
461      }
462      const text = expandNumbers(expandRanges(e.text, await numbered($)), lookup)
463      return next(text === e.text ? e : { ...e, text })
464    }
465    if (shown.input === null) {
466      return { drop: '프리셋 편집 중이에요. q로 편집을 끝낸 뒤 보내 주세요' }
467    }
468    const editing = shown.input
469    const text = e.text.trim()
470    await submitInput($, editing, text)
471    void $.prompt.fill({ text: '' })
472    return { drop: text === '' && editing.kind !== 'title' ? '문구가 비어 있어서 저장하지 않았어요' : SAVED[editing.kind] }
473  })
474
475  // 편집하는 동안 입력창 아래 안내 줄을 vim의 모드 표시로 바꾼다. 두 번 치는 키의 첫 글자(d, g)는 vim처럼 옆에 보인다.
476  on('ui.render', { component: 'PromptHint' }, async ($, e, next) => {
477    const shown = await read($, mode)
478    if (shown.kind !== 'edit') {
479      return next(e)
480    }
481    const hint =
482      shown.input === null
483        ? `-- NORMAL --  ${shown.pending ?? ''}`.trimEnd()
484        : '-- INSERT --  Enter 저장 · $q 취소'
485    return next({ ...e, props: { ...e.props, hint } })
486  })
487
488  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
489    // 띠는 터미널과 데스크톱에만 그려진다.
490    if (e.props.hasSurvey || (e.surface !== 'terminal' && e.surface !== 'desktop')) {
491      return next(e)
492    }
493    const presets = await current($)
494    const shown = await read($, mode)
495    const { Box, Button, Text } = $.ui.resolve(e)
496
497    if (shown.kind === 'view') {
498      const below = await next(e)
499      const folded = await isCompact($)
500      // 번호는 다음 제안 다음부터 이어 붙인다. 작업 중에는 다음 제안이 숨으므로 1부터다.
501      // 프리셋 하나는 버튼 두 개다. 번호(`$1:`)는 클릭하면 문구를 입력창에 넣기만 하고, 문구는 클릭하면 바로 보낸다.
502      // 입력창에 `$1 `처럼 번호와 스페이스를 치면 번호를 클릭하지 않아도 그 자리에 들어간다(prompt.edit).
503      let number = e.props.isWorking ? 0 : await suggestionCount($)
504      const item = (reply: Reply) => {
505        number += 1
506        // 접으면 제목을, 펼치면 문구를 보인다. 보이는 글이 /명령으로 시작하면 그 부분만 칠한다.
507        // 펼쳐도 한 줄만 쓴다. 줄바꿈은 띄어쓰기로 잇고, 폭을 넘으면 말줄임표로 자른다. 전체 문구는 편집 화면에서 보인다.
508        const label = folded ? shortTitle(reply) : reply.text.replace(/\s*\n\s*/g, ' ')
509        const command = parseCommand(reply.text)
510        const prefix = command === null ? '' : `/${command.command}`
511        const isCommand = prefix !== '' && label.startsWith(prefix)
512        return (
513          <Box key={`item:${reply.id}`} flexDirection="row" columnGap={1}>
514            <Button
515              key={`fill:${reply.id}`}
516              label={numberLabel(number)}
517              plain
518              onPress={() => {
519                void $.prompt.fill({ text: reply.text })
520              }}
521            >
522              <Text color={ACCENT}>{numberLabel(number)}</Text>
523            </Button>
524            <Button
525              key={`send:${reply.id}`}
526              label={label}
527              plain
528              onPress={() => {
529                void send($, reply.text)
530              }}
531            >
532              <Text wrap="truncate-end">
533                {/* 스킬이나 슬래시 명령은 명령 부분만 번호와 같은 색으로 칠해 일반 문장과 구분한다. */}
534                {isCommand && <Text color={ACCENT}>{prefix}</Text>}
535                {isCommand ? label.slice(prefix.length) : label}
536              </Text>
537            </Button>
538          </Box>
539        )
540      }
541      // 펼치면 다음 제안과 같은 모양으로, 제목 줄 아래에 한 줄에 하나씩 둔다. 그래서 두 목록의 번호가 같은 열에 선다.
542      // 접으면 한 범위를 한 줄에 `4: 제목 | 5: 제목`으로 잇는다.
543      const group = (scope: Scope, list: Reply[]) =>
544        folded ? (
545          <Box key={`group:${scope}`} flexDirection="row" flexWrap="wrap" columnGap={1} paddingLeft={2}>
546            {list.flatMap((reply, i) => [
547              ...(i > 0 ? [<Text key={`sep:${reply.id}`} dimColor>|</Text>] : []),
548              item(reply),
549            ])}
550          </Box>
551        ) : (
552          list.map(reply => (
553            <Box key={`line:${reply.id}`} paddingLeft={2}>
554              {item(reply)}
555            </Box>
556          ))
557        )
558      // 0은 프리셋 줄만 접고 편다. 다음 제안은 늘 전체 문구로 보인다.
559      const rows = (
560        <Box flexDirection="column">
561          <Box flexDirection="row" columnGap={2}>
562            <Text dimColor>전역</Text>
563            {/* 입력창에 $e를 치거나 클릭하면 편집 화면을 연다. 그 뒤로는 키 하나로 다 고친다. $0은 접고 편다. */}
564            <Button key="edit" label="$e: 편집" plain onPress={() => openEditor($)}>
565              <Text>
566                <Text color={ACCENT}>$e:</Text> <Text dimColor>편집</Text>
567              </Text>
568            </Button>
569            <Button key="compact" label={folded ? '$0: 펼치기' : '$0: 접기'} plain onPress={() => toggleCompact($)}>
570              <Text>
571                <Text color={ACCENT}>$0:</Text> <Text dimColor>{folded ? '펼치기' : '접기'}</Text>
572              </Text>
573            </Button>
574          </Box>
575          {presets.global.length > 0 && group('global', presets.global)}
576          {presets.project.length > 0 && <Text dimColor>로컬</Text>}
577          {presets.project.length > 0 && group('project', presets.project)}
578        </Box>
579      )
580      return withBandSection(below, 'quick-replies', ORDER, rows)
581    }
582
583    // 편집 화면: 띠를 혼자 쓰고, vim처럼 키 하나(또는 dd, gg)로 동작한다. 키는 editorKey에 적었다.
584    const all = ordered(presets)
585    const selected = all.find(item => item.reply.id === shown.selected) ?? null
586    const setEdit = (patch: Partial<Extract<Mode, { kind: 'edit' }>>) =>
587      update($, mode, m => (m.kind === 'edit' ? { ...m, ...patch } : m))
588    const projectName = presets.root.split('/').filter(Boolean).at(-1) ?? presets.root
589
590    const item = (entry: { reply: Reply; scope: Scope }, index: number) => {
591      const isSelected = entry.reply.id === shown.selected
592      return (
593        <Box key={`row:${entry.reply.id}`} flexDirection="row">
594          <Text color={ACCENT}>{isSelected ? '▸ ' : '  '}</Text>
595          <Button
596            key={`select:${entry.reply.id}`}
597            label={entry.reply.text}
598            plain
599            {...(index < 9 ? { hotkey: String(index + 1) } : {})}
600            onPress={() => setEdit({ selected: entry.reply.id, input: null })}
601          >
602            <Text>
603              {entry.reply.text}
604              {entry.reply.title !== undefined && <Text dimColor>{`  제목: ${entry.reply.title}`}</Text>}
605            </Text>
606          </Button>
607        </Box>
608      )
609    }
610    const group = (title: string, scope: Scope) => {
611      const entries = all.filter(entry => entry.scope === scope)
612      return (
613        <Box flexDirection="column">
614          <Text dimColor>{title}</Text>
615          {entries.length === 0 && <Text dimColor>  (비어 있음)</Text>}
616          {entries.map(entry => item(entry, all.indexOf(entry)))}
617        </Box>
618      )
619    }
620    // 버튼을 클릭해도 입력창에 그 글자를 친 것과 같은 동작을 한다. 소문자 한 글자는 띠의 단축키로 달아 `a: 라벨`로 그려진다.
621    // 버튼 단축키는 소문자 한 글자만 받으므로, 대문자(J, K)와 두 글자(dd)는 단축키 없이 글자만 직접 그린다. dd는 두 번 눌러야 지운다.
622    const action = (key: string, typed: string, label: string) =>
623      /^[a-z]$/.test(typed) ? (
624        <Button key={key} label={label} hotkey={typed} plain onPress={() => void editorKey($, typed)} />
625      ) : (
626        <Button key={key} label={`${typed}: ${label}`} plain onPress={() => void editorKey($, typed[0] ?? '')}>
627          <Text>
628            <Text color={ACCENT}>{typed}:</Text> {label}
629          </Text>
630        </Button>
631      )
632
633    let inputRow = null
634    if (shown.input !== null) {
635      const editing = shown.input
636      const title =
637        editing.kind === 'rename'
638          ? '문구 수정'
639          : editing.kind === 'title'
640            ? '제목'
641            : editing.scope === 'global'
642              ? '전역에 추가'
643              : '로컬에 추가'
644      inputRow = (
645        <Box flexDirection="row" columnGap={1}>
646          <Text color={ACCENT}>{title}</Text>
647          <Text dimColor>
648            {editing.kind === 'title' ? '프리셋을 접었을 때 보일 짧은 이름을 입력창에 쓰고 Enter를 눌러 주세요. 비워 두면 문구를 줄여서 보여 줘요' : '입력창에 문구를 쓰거나 /스킬 이름과 문구를 함께 쓰고 Enter를 눌러 주세요'}
649          </Text>
650          <Button key="cancel" label="$q: 취소" plain onPress={() => cancelInput($)}>
651            <Text>
652              <Text color={ACCENT}>$q:</Text> <Text dimColor>취소</Text>
653            </Text>
654          </Button>
655        </Box>
656      )
657    }
658
659    const editor = (
660      <Box flexDirection="column">
661        <Box flexDirection="row" columnGap={2}>
662          <Text bold>프리셋 편집</Text>
663          {action('add', 'o', selected?.scope === 'project' ? '로컬에 추가' : '전역에 추가')}
664          {shown.deleted !== undefined && action('undo', 'u', '되살리기')}
665          {action('done', 'q', '완료')}
666        </Box>
667        {group('전역 (모든 저장소)', 'global')}
668        {group(`로컬 (${projectName})`, 'project')}
669        {inputRow}
670        {selected === null ? (
671          <Text dimColor>입력창에 j, k 또는 프리셋 번호를 쳐서 고르면 문구 수정, 제목 달기, 삭제, 이동을 할 수 있어요.</Text>
672        ) : (
673          <Box flexDirection="row" columnGap={2}>
674            <Text dimColor>고른 프리셋</Text>
675            {action('act-edit', 'i', '문구 수정')}
676            {action('act-title', 't', '제목')}
677            {action('act-delete', 'dd', '삭제')}
678            {action('act-move', 'm', selected.scope === 'global' ? '로컬로' : '전역으로')}
679            {action('act-up', 'K', '위로')}
680            {action('act-down', 'J', '아래로')}
681          </Box>
682        )}
683      </Box>
684    )
685    return exclusiveBand(editor)
686  })
687}
688
hooks/band.ts 148 lines
1// 입력창 위 띠(AbovePrompt)를 여러 모드가 나눠 쓰는 약속.
2// 이 파일은 quick-replies, next-prompts, relaunch에 똑같이 들어 있다. 고칠 때는 셋 다 고친다.
3//
4// 띠 자리에는 한 트리만 그려지므로, 각 모드는 아래 모양의 "띠 틀"을 주고받는다.
5//   Box(key=oobg-band, column)
6//     Box(key=oobg-band:<순서>:<이름>)   ← 각 모드의 줄, 순서대로
7// 모드는 next(e)로 받은 틀에 자기 줄만 끼워 넣어 돌려준다. 틀이 아니면 새로 만든다.
8//
9// 번호($1~$9)는 각 모드가 스스로 매긴다. 다음 제안이 $1부터, 프리셋은 떠 있는 제안 개수 다음부터다.
10// 띠를 합치는 순서는 모드마다 다르게 보이므로 번호를 여기서 매기지 않는다.
11// 입력창에 `$2 `, `$12 `처럼 번호 뒤에 스페이스를 치면 그 번호의 문구로 바뀐다(`typedNumber`). 빈 입력창의 숫자 하나는 더 이상 버튼을 누르지 않는다.
12// 스페이스 없이 `$12`에서 바로 Enter를 눌러도 보낼 때 문구로 바꾼다(`expandNumbers`).
13// `$2-$4 `처럼 범위를 치면 그 번호들의 문구를 한 줄씩 넣는다(`typedRange`, `expandRanges`).
14// `$e`, `$0`처럼 `$` 뒤의 글자 하나는 모드가 정한 동작을 부른다(`typedAfterDollar`).
15//
16// 한 모드가 띠를 혼자 써야 할 때(편집 화면 등)는 `exclusiveBand`로 만든 틀을 돌려준다.
17// 다른 모드는 그 틀을 보면 자기 줄을 넣지 않고 그대로 넘긴다.
18import type { PromptEditInput, RenderElement, RenderNode } from 'claude-code'
19
20const BAND_KEY = 'oobg-band'
21const EXCLUSIVE_KEY = 'oobg-band-exclusive'
22const SECTION_PREFIX = `${BAND_KEY}:`
23
24function isElement(node: RenderNode | undefined | null): node is RenderElement {
25  return typeof node === 'object' && node !== null && 'type' in node
26}
27
28function keyOf(node: RenderNode): string | undefined {
29  if (!isElement(node) || node.type !== 'Box') {
30    return undefined
31  }
32  const key = node.props?.key
33  return typeof key === 'string' ? key : undefined
34}
35
36function orderOf(node: RenderNode): number {
37  return Number(keyOf(node)?.split(':')[1] ?? 0)
38}
39
40// 띠에 보이는 번호 표시.
41export const numberLabel = (n: number) => `$${n}:`
42
43// 방금 친 글자 하나가 `$` 바로 뒤이고 그 `$`가 글 처음이나 공백 뒤에 있으면 그 글자를 낸다.
44export function typedAfterDollar(e: PromptEditInput): string | undefined {
45  if (e.key === undefined || !/^[0-9a-z]$/.test(e.inputText) || e.start !== e.end || e.text[e.start - 1] !== '$') {
46    return undefined
47  }
48  const before = e.text[e.start - 2]
49  return before === undefined || /\s/.test(before) ? e.inputText : undefined
50}
51
52// `$12`처럼 번호를 친 뒤 스페이스를 치면 그 번호와 `$`의 자리를 낸다. 스페이스로 끝을 알려야 두 자리 번호도 고를 수 있다.
53// `$`는 글 처음이나 공백 뒤에 있어야 한다. 바꿀 때는 `next({ ...e, start: typed.start, inputText: 문구 + ' ' })`로 `$`부터 친 스페이스까지 덮고, 이어 쓰기 좋게 문구 뒤에 스페이스 하나를 붙인다.
54export function typedNumber(e: PromptEditInput): { n: number; start: number } | undefined {
55  if (e.key === undefined || e.inputText !== ' ' || e.start !== e.end) {
56    return undefined
57  }
58  const match = /(?:^|\s)\$([1-9][0-9]*)$/.exec(e.text.slice(0, e.start))
59  return match === null ? undefined : { n: Number(match[1]), start: e.start - match[1]!.length - 1 }
60}
61
62// 스페이스 없이 보낸 글에 남은 `$12` 같은 번호를 문구로 바꾼다. `$`는 글 처음이나 공백 뒤, 번호 뒤는 공백이나 글 끝이어야 한다.
63// `lookup`이 문구를 주지 않는 번호(다른 모드의 번호, 없는 번호)는 그대로 둔다.
64export function expandNumbers(text: string, lookup: (n: number) => string | undefined): string {
65  return text.replace(/(^|\s)\$([1-9][0-9]*)(?=\s|$)/g, (whole, before: string, digits: string) => {
66    const phrase = lookup(Number(digits))
67    return phrase === undefined ? whole : before + phrase
68  })
69}
70
71// `$2-$4`처럼 범위를 쳐서 여러 문구를 한 번에 넣는다. `$4-$2`처럼 거꾸로 치면 거꾸로 넣는다.
72// 문구마다 줄을 바꾸고, 글 맨 앞이 아니면 앞 글과 빈 줄 하나를 둔다. 앞 글 끝의 공백은 지운다.
73// 범위의 번호를 모두 `lookup`으로 찾을 수 있을 때만 바꾼다. 다음 제안과 프리셋이 섞인 범위는 둘 다 아는 quick-replies가 바꾼다.
74export type Range = { from: number; to: number; start: number }
75
76// 범위를 넣을 글. `start`는 범위가 덮는 자리의 처음이다. 찾을 수 없는 번호가 있으면 undefined.
77export function rangeText(range: Range, lookup: (n: number) => string | undefined): string | undefined {
78  const step = range.from <= range.to ? 1 : -1
79  let text = range.start === 0 ? '' : '\n\n'
80  for (let n = range.from; n !== range.to + step; n += step) {
81    const phrase = lookup(n)
82    if (phrase === undefined) {
83      return undefined
84    }
85    text += `${phrase}\n`
86  }
87  return text
88}
89
90// `$2-$4` 뒤에 스페이스를 치면 그 범위와 덮을 자리를 낸다. 자리는 앞 글 끝의 공백부터다.
91// 바꿀 때는 `next({ ...e, start: range.start, inputText: rangeText(range, lookup) })`로 친 스페이스까지 덮는다.
92export function typedRange(e: PromptEditInput): Range | undefined {
93  if (e.key === undefined || e.inputText !== ' ' || e.start !== e.end) {
94    return undefined
95  }
96  const match = /(?:^|\s)\$([1-9][0-9]*)-\$([1-9][0-9]*)$/.exec(e.text.slice(0, e.start))
97  if (match === null) {
98    return undefined
99  }
100  const start = e.text.slice(0, e.start - match[0].trimStart().length).trimEnd().length
101  return { from: Number(match[1]), to: Number(match[2]), start }
102}
103
104// 스페이스 없이 보낸 글에 남은 `$2-$4` 같은 범위를 문구들로 바꾼다. 바꾸는 규칙은 `typedRange`와 같다.
105export function expandRanges(text: string, lookup: (n: number) => string | undefined): string {
106  return text.replace(/(^|\s+)\$([1-9][0-9]*)-\$([1-9][0-9]*)(?=\s|$)/g, (whole, _before, from: string, to: string, start: number) => {
107    return rangeText({ from: Number(from), to: Number(to), start }, lookup) ?? whole
108  })
109}
110
111// 띠를 혼자 쓰는 틀. 다른 모드는 이 틀에 줄을 넣지 않는다.
112export function exclusiveBand(section: RenderNode): RenderElement {
113  return { type: 'Box', props: { key: EXCLUSIVE_KEY, flexDirection: 'column', marginTop: 1 }, children: [section] }
114}
115
116// `below`(next(e)가 돌려준 트리)에 이 모드의 줄을 넣은 띠 틀을 돌려준다.
117// `section`이 null이면 이 모드의 줄을 뺀다. 남은 줄이 하나도 없으면 `below`를 그대로 돌려준다.
118export function withBandSection(
119  below: RenderElement,
120  name: string,
121  order: number,
122  section: RenderNode | null,
123): RenderElement {
124  if (below.type === 'Box' && below.props?.key === EXCLUSIVE_KEY) {
125    return below
126  }
127  const ownKey = `${SECTION_PREFIX}${order}:${name}`
128  const isBand = below.type === 'Box' && below.props?.key === BAND_KEY
129  const others = isBand
130    ? (below.children ?? []).filter(child => {
131        const key = keyOf(child)
132        return key !== undefined && key.startsWith(SECTION_PREFIX) && key !== ownKey
133      })
134    : []
135  const mine: RenderNode[] =
136    section === null
137      ? []
138      : // 줄마다 위에 한 칸을 띄워 제안과 프리셋이 구분되어 읽히게 한다.
139        [{ type: 'Box', props: { key: ownKey, flexDirection: 'column', marginTop: 1 }, children: [section] }]
140  const sections = [...others, ...mine].sort((a, b) => orderOf(a) - orderOf(b))
141
142  if (sections.length === 0) {
143    return isBand ? { type: 'Box', props: { key: BAND_KEY }, children: [] } : below
144  }
145  // 띠와 입력창 사이의 빈 줄은 Claude Code가 늘 두는 간격이다. 음수 여백으로 당기면 띠가 아예 그려지지 않아 그대로 둔다.
146  return { type: 'Box', props: { key: BAND_KEY, flexDirection: 'column' }, children: sections }
147}
148
hooks/title.ts 124 lines
1// 프리셋 문구를 접은 띠에 보일 짧은 제목으로 줄이는 부분. $를 쓰지 않는 순수 함수만 둔다.
2import type { Reply } from '../types'
3
4// 접은 띠에서 한 줄에 여러 개가 놓이므로 제목은 이 폭까지만 쓴다. 한글은 두 칸이라 한글로는 12자, 영어로는 24자다.
5export const MAX_TITLE_COLUMNS = 24
6// 모델 답의 길이 한도. 제목 하나를 담은 JSON 배열이 넉넉히 들어간다.
7export const MAX_TITLE_TOKENS = 60
8// 제목이 요청에 쓴 말을 이만큼 이어서 그대로 옮기면, 제목이 아니라 규칙이나 요청 틀을 되읊은 것으로 본다.
9const ECHO_CHARS = 10
10const ASK = '제목(JSON 문자열 배열):'
11
12export const TITLE_SYSTEM = [
13  '너는 자주 보내는 요청 문구에 짧은 제목을 붙인다.',
14  '규칙:',
15  `- 한글이면 ${MAX_TITLE_COLUMNS / 2}자, 영어면 ${MAX_TITLE_COLUMNS - 4}자 이내의 제목 하나만 쓴다. 번호, 설명, 마크다운은 붙이지 않는다.`,
16  '- 문구의 언어와 말투를 따르고, 무엇을 하는 요청인지 드러나게 줄인다.',
17  '- 문구가 /로 시작하면 슬래시 명령이다. 명령 이름보다 그 요청이 하는 일로 짓는다.',
18  '- 답은 제목 하나를 담은 JSON 문자열 배열만 쓴다. 배열 앞뒤에 설명이나 머리말을 붙이지 않는다.',
19].join('\n')
20
21export function titlePrompt(text: string): string {
22  return ['<문구>', text, '</문구>', ASK].join('\n')
23}
24
25// 터미널에서 두 칸을 차지하는 글자: 한글, 한자, 가나, 전각 기호, 그림 문자.
26const WIDE = /[\u1100-\u115f\u2e80-\u303e\u3041-\u33ff\u3400-\u4dbf\u4e00-\u9fff\ua960-\ua97f\uac00-\ud7a3\uf900-\ufaff\ufe30-\ufe4f\uff00-\uff60\uffe0-\uffe6\u{1f300}-\u{1faff}]/u
27
28function columns(text: string): number {
29  let width = 0
30  for (const char of text) {
31    width += WIDE.test(char) ? 2 : 1
32  }
33  return width
34}
35
36function cut(text: string): string {
37  if (columns(text) <= MAX_TITLE_COLUMNS) {
38    return text
39  }
40  let kept = ''
41  for (const char of text) {
42    if (columns(kept + char) > MAX_TITLE_COLUMNS) {
43      break
44    }
45    kept += char
46  }
47  return `${kept.trimEnd()}…`
48}
49
50// 답에서 JSON 배열을 찾아 그 안의 문자열을 꺼낸다. 배열 앞뒤의 머리말, 맺음말, 코드 울타리는 버린다.
51// {"title": [...]}처럼 감싼 객체면 그 안의 배열을, 항목이 객체면 그 안의 첫 문자열을 읽는다.
52// 길이 한도에서 잘려 배열이 닫히지 않았으면 따옴표가 닫힌 문자열까지 건진다. 배열이 없으면 undefined.
53// next-prompts의 같은 이름 함수와 같다. 모드끼리는 코드를 나눠 쓰지 못한다.
54export function jsonStrings(reply: string): string[] | undefined {
55  const text = (item: unknown) =>
56    typeof item === 'string' ? item : Object.values(item ?? {}).find(v => typeof v === 'string')
57  const ends = [...reply.matchAll(/\]/g)].map(m => m.index)
58  for (const start of [...reply.matchAll(/\[/g)].map(m => m.index)) {
59    // 머리말의 "[참고]"나 문자열 안의 ]처럼 배열이 아닌 자리는 건너뛴다.
60    for (const end of ends.filter(end => end > start)) {
61      try {
62        const value: unknown = JSON.parse(reply.slice(start, end + 1))
63        // 머리말의 "[1]"처럼 문자열이 하나도 없는 배열은 답이 아니다. 빈 배열은 "고를 게 없다"는 답이다.
64        const strings = Array.isArray(value) ? value.map(text).filter(item => item !== undefined) : []
65        if (Array.isArray(value) && (value.length === 0 || strings.length > 0)) {
66          return strings
67        }
68      } catch {
69        // 다음 ]까지 넓혀 본다.
70      }
71    }
72  }
73  // 항목이 객체면 키는 버리고 값만 건진다.
74  const open = reply.search(/\[\s*["{]/)
75  if (open === -1) {
76    return undefined
77  }
78  const rest = reply.slice(open)
79  const strings = /^\[\s*\{/.test(rest) ? /:\s*("(?:[^"\\]|\\.)*")/g : /("(?:[^"\\]|\\.)*")/g
80  return [...rest.matchAll(strings)].flatMap(m => {
81    try {
82      return [JSON.parse(m[1]!) as string]
83    } catch {
84      return []
85    }
86  })
87}
88
89const PROMPT_TEXT = `${TITLE_SYSTEM}\n${ASK}`
90
91function echoes(line: string): boolean {
92  for (let i = 0; i + ECHO_CHARS <= line.length; i += 1) {
93    if (PROMPT_TEXT.includes(line.slice(i, i + ECHO_CHARS))) {
94      return true
95    }
96  }
97  return false
98}
99
100// 답의 JSON 배열에서 첫 문자열을, 배열이 없으면 규칙을 어긴 답으로 보고 첫 줄을 제목으로 쓴다.
101// 기호와 따옴표는 걷어 내고, 길면 자른다. 요청을 되읊었거나 쓸 게 없으면 빈 문자열.
102export function parseTitle(reply: string): string {
103  const lines = jsonStrings(reply) ?? reply.split('\n')
104  // 접은 띠는 마크다운을 그리지 않아 **굵게**와 `코드`가 기호째 보인다.
105  const line = (lines.find(l => l.trim() !== '') ?? '')
106    .trim()
107    .replace(/\*\*(.+?)\*\*/g, '$1')
108    .replace(/`([^`\n]+)`/g, '$1')
109    .replace(/^(제목\s*[::]|\d+[.)]|[-*•](?=\s))\s*/, '')
110    .replace(/^["'“‘`](.*)["'”’`]$/, '$1')
111    .trim()
112  return echoes(line) ? '' : cut(line)
113}
114
115// 짧은 문구는 그대로 제목이 되니 모델에 묻지 않는다.
116export function needsTitle(reply: Reply): boolean {
117  return reply.title === undefined && columns(reply.text) > MAX_TITLE_COLUMNS
118}
119
120// 접은 띠에 보일 이름. 제목이 아직 없으면 문구를 줄여 보인다.
121export function shortTitle(reply: Reply): string {
122  return reply.title ?? cut(reply.text)
123}
124
types/index.d.ts 37 lines
1/**
2 * 프리셋 하나. `text`는 보내는 문구, `title`은 접은 띠에 보이는 짧은 이름(없으면 `text`를 줄여 쓴다).
3 * `autoTitle`은 제목을 모델이 지었다는 표시다. 문구를 고치면 다시 짓는다. 사람이 단 제목에는 없다.
4 */
5export type Reply = { id: string; text: string; title?: string; autoTitle?: true }
6
7/** 프리셋이 어디에 저장되는가: 모든 저장소에 보이는 `global`, 지금 저장소에만 보이는 `project`. */
8export type Scope = 'global' | 'project'
9
10/** 편집 화면의 입력칸: 새 프리셋을 쓰는 `add`, 고른 프리셋의 문구를 고치는 `rename`, 제목을 고치는 `title`. */
11export type EditInput = { kind: 'add'; scope: Scope } | { kind: 'rename'; id: string } | { kind: 'title'; id: string }
12
13/** `dd`로 지운 프리셋과 그 자리. `u`로 그 자리에 되살린다. */
14export type Deleted = { reply: Reply; scope: Scope; index: number }
15
16/**
17 * 띠의 화면: 프리셋 버튼만 보이는 `view`, 목록을 고치는 `edit`.
18 * `selected`는 커서가 있는 프리셋, `input`은 지금 열린 입력칸(없으면 null)이다.
19 * `pending`은 `dd`, `gg`처럼 두 번 치는 키의 첫 글자, `deleted`는 마지막으로 지운 프리셋이다.
20 */
21export type Mode =
22  | { kind: 'view' }
23  | { kind: 'edit'; selected: string | null; input: EditInput | null; pending?: string; deleted?: Deleted }
24
25declare module 'claude-code' {
26  interface PluginState {
27    'quick-replies': {
28      repo: string | null
29      globalReplies: Reply[] | null
30      projectReplies: Reply[] | null
31      mode: Mode
32      /** 프리셋 줄을 접어 한 범위를 한 줄에 제목만으로 보이는가. 다음 제안은 접지 않는다. 읽기 전에는 null. */
33      compact: boolean | null
34    }
35  }
36}
37