SLOPSHOPPER

desk-look

Claude Code mod that redraws the terminal transcript to look like the Code tab of the Claude desktop app: prompt bubbles, markdown tables, mermaid diagrams…

panebandspinnerrowsguardcommand
★ 2v0.59.2MITupdated 2026-10-26KyongSik-Yoon/cc-desktop-mod/desk-look
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · desk-look
│ ┃ desk-activity ✕ ╭────────────────────────────────────────────╮ │ ┃ Last turn · 42s ╭───────────────────│ desk-look │ │ ┃ │ fix the failing au│ Select the text to quote in the │ │ ┃ Main ░──────────────────────────────── ╰───────────────────│ conversation with the mouse first. │ │ ┃ ─ ╰────────────────────────────────────────────╯ │ ┃ 0 ⏺ Read(src/auth.ts) │ ┃ 42s ⎿ Read 6 lines │ ┃ ░ explore ▓ edit ▒ test ━ Edited │ ┃ command ━ agent ─ Responding ⏺ Bash(bun test) │ ┃ ⎿ 3 pass, 1 fail │ ┃ Flow │ ┃ 00:00 ░ Read · Grep Done. I made refresh reject expired claims and added an audit call. │ ┃ 00:00 ◉ I updated src/auth.ts to reject ex… │ ✻ Worked… ❝ quote │ 3 commands (1 failed) │ ╭──────────────────────────────────────────────────────────────────── │ │ Edited 3 files +14 −1 │ │ auth.ts │ │ audit.ts │ │ cache.ts │ ╰──────────────────────────────────────────────────────────────────── │ │ › /desk-preview │ ⎿ desk-look: Nothing previewed yet. Open one with /desk-preview <f │ │ ··● Thinking 0s ⟨Claude Code's own drawing⟩ ✓ I updated src/auth.ts to reject expired claims and added an audit call. step 1 ✕ app feat/auth-refresh chin-diff  #NaN ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
⟨Claude Code's own drawing⟩ ✓ I updated src/auth.ts to reject expired claims and added an audit call. step 1 ✕ app feat/auth-refresh chin-diff  #NaN
Pane · desk-activity
Last turn · 42s step 1 Main ░──────────────────────────────────────────── 0 42s ░ explore ▓ edit ▒ test ━ command ━ agent ─ Responding Flow 00:00 ░ Read · Grep 00:00 ◉ I updated src/auth.ts to reject expired claims and…
Pane · desk-sessions
0 recent sessions r: ↻ f: Search Search: title or folder ⏎ Open first result
Pane · desk-tasks
No background tasks in this session yet.
Pane · desk-preview
Nothing previewed yet. Open one with /desk-preview <file>.
Pane · desk-context
Context ◑ 49% r: ↻ ▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱ 97.4k / 200.0k tokens Usage limits 5-hour ▰▰▰▱▱▱▱▱▱▱ 31% This session cost $0.42
Pane · desk-diff
● Uncommitted ○ Branch ○ Commits Edited 1 file +2 −1 r: ↻ src/auth.ts Revert
Pane · desk-pr
 #NaN r: ↻ Open · ← · +0 −0 Checks none Unresolved reviews unavailable
Spinner
··● Thinking 0s
Turn line
✻ Worked… ❝ quote 3 commands (1 failed) ╭──────────────────────────────────────────────────────────────────────╮ │ Edited 3 files +14 −1 │ │ auth.ts │ │ audit.ts │ │ cache.ts │ ╰──────────────────────────────────────────────────────────────────────╯
Your message
╭─────────────────────────────────────────────────────╮ │ fix the failing auth test and add an audit log call │ ╰─────────────────────────────────────────────────────╯
Claude's reply
Done. I made refresh reject expired claims and added an audit call.
Tool row
Edited
README

desk-look

A Claude Code mod that makes the terminal UI look and work like the Code tab of the Claude desktop app. It changes only how the transcript and the area around the prompt are drawn; the engine is left as it is, and nothing changes in the desktop app.

  • Prompt bubbles, desktop-style markdown (full-width tables, mermaid diagrams, alert boxes), tool calls folded into one clickable line, cards for subagents, plans, questions and each turn's edited files
  • A band above the prompt with the repository, branch, +N −M, pull request checks, context usage, background tasks, and unread Slack messages when desk-slack is installed
  • Side panes: diffs with line comments (/desk-diff), what ran this turn (/desk-activity), background tasks (/desk-tasks), the pull request (/desk-pr), Markdown preview (/desk-preview), context and usage limits (/desk-context) and recent sessions (/desk-sessions)
  • English or Korean labels
  • The Asana and Slack panes are separate plugins from the same marketplace, desk-asana and desk-slack; install them only if you use them

Screenshots, settings and details: https://github.com/KyongSik-Yoon/cc-desktop-mod

What it runs, reads and sends

desk-look collects no data and makes no network request of its own. Everything it reads stays on your machine, except what is listed under "Sends".

Runs (each one by name, with its whole command written at the call; no shell and no inline scripts, from hooks/register.tsx, hooks/ask.tsx and the files they import):

  • git: branch, diff stats and diffs for the current repository, the branch list when you pick a diff base, and the hidden lines of a file (from the working tree, or from a commit with git cat-file) when you click N unmodified lines; git restore only when you press Revert twice
  • gh (GitHub) and glab (GitLab): read the current branch's pull request or merge request, and merge it only when you press Merge twice. They use the login you already have in those tools; desk-look never reads or passes a token
  • claude agents --json: list the sessions open right now, for the status chips in /desk-sessions; claude stop <id>: only when you pick a running background session there, to take it into this window (its conversation is kept)
  • herdr pane list, herdr workspace focus and herdr tab focus: only inside herdr, when you pick a session in /desk-sessions that is open in another terminal, to switch to the tab where it is open
  • wl-copy: copy cd <folder> && claude --resume <id> to the clipboard from /desk-sessions, when switching this window to a session in another folder is blocked
  • claude plugin marketplace update and claude plugin update: only when you run /desk-update, for desk-look and for desk-asana and desk-slack (a plugin that is not installed just fails and is not mentioned)
  • id -u and od -N 24: find this session's temporary folder (/tmp/claude-<uid>) for pasted images and the preview's browser page, and read the first 24 bytes of each PNG for its size
  • head -c and tail -c: read the start (working folder) and end (title) of a session file over 320 KB for /desk-sessions
  • mktemp -d, mkfifo, cat, tee and rm -rf: the question card waits for your answer on a named pipe in a temporary folder (cat reads it, the card's buttons write the answer with tee; each press also writes a counter to a touched file there with tee, which a Remote Control session uses to tell you are still at the terminal) and removes the folder afterwards
  • xdg-open (on macOS open): only when you press o in the preview pane, to open the document in your default browser. desk-look first writes the page to /tmp/claude-<uid>/desk-look/<name>.html ($.fs.write) and leaves it there for the browser. A page with mermaid diagrams makes the browser load mermaid from cdn.jsdelivr.net; the document itself goes nowhere

Those two folders are the only places desk-look writes files

Reads: while a shell command Claude runs takes longer than 3 seconds, every 3 seconds, Claude Code's child processes in /proc (/proc/<pid>/task/<pid>/children, /proc/<pid>/stat, /proc/<pid>/io and /proc/uptime), following only the shell that command started and the programs under it, for the CPU and I/O figures in the progress band (Linux only, nothing is kept after the turn); the output file of a background shell this turn started, every 3 seconds while /desk-activity is open and the shell runs, for its last line; the omarchy theme colors (~/.local/state/omarchy/current/theme/colors.toml), Markdown files you open in the preview pane, recent session files (~/.claude/projects) for /desk-sessions, session state files (~/.claude/sessions) to see whether Remote Control is attached to this session, the list of this session's pasted images (/tmp/claude-<uid>/…/images), herdr's kitty_graphics setting (~/.config/herdr/config.toml), the values desk-asana and desk-slack publish for it (the unread Slack count for the ✉ chip, whether they are loaded, and which of their panes /desk-fold folded), the conversation and usage data Claude Code hands to the mod, to draw the transcript, cards and panes, and the text you last selected on screen ($.ui.selection), only when you press ❝ quote or run /desk-quote, to put it in the prompt.

Sends: only through gh and glab, to GitHub or GitLab, for the pull request reads and merges above. Diff line comments you write in /desk-diff are attached to your next prompt as context, so they go to Claude with that prompt like the rest of it.

Hooks and what they do

Every hook below passes the event on with next(e) and only watches the result, except where it says otherwise.

  • ui.render, ui.scroll: draw the transcript, cards, chips and panes in the desktop style
  • session.end: after /resume or /clear in the same window, read the session's state again (the engine sends no session.start for the session it switches to)
  • session.start, session.append, turn.start, turn.step, turn.complete: keep the folded tool lines, the end-of-turn card, the background tasks pane (an agent's model and token counts) and the PR chip up to date; at the end of a turn, open a Markdown file Claude wrote in the preview pane
  • prompt.submit: note whether a prompt came from the terminal or Remote Control (for the question card), read background-task notifications, and attach pending diff line comments to a typed prompt as context (never to a slash command)
  • tool.call: count each edit's added and removed lines for the end-of-turn card, and note each call's tool, start, end and result (the main conversation's and its agents') for the progress band and /desk-activity. For AskUserQuestion it shows the question card and returns the answer you pick (or hands the question to Claude Code's own dialog, or reports that you closed it). For desk-look's own preview tool it opens the preview pane and returns what it opened
  • command.run: handles desk-look's own /desk-* commands only

Calls it makes on its own, each after you press something: /resume <id> when you pick a session in /desk-sessions, after /cd <folder> when it is in another folder (if running them is blocked, it places /resume <id> in the prompt or copies a shell command instead), TaskStop when you press ■ Stop twice on a background task, and switching the main view to an agent's transcript (or back) when you press Open in main view (Main conversation) in the background tasks pane. It also registers its /desk-* commands and the preview tool, and reads Claude Code's language setting. At the start of a turn, until MCP servers have connected (for at most 5 turns per session, and never again once it has decided), it lists Claude Code's tools ($.tool.list) to see whether an Asana or Slack MCP server is there without desk-asana or desk-slack, and if so says once where those panes went (remembered in its plugin store).

hooks/vendor/lovely-mermaid.js is lovely-mermaid 0.3.3 (Apache-2.0, hooks/vendor/LICENSE.lovely-mermaid), bundled without minification, used to draw mermaid diagrams. It runs no programs and makes no requests.

License

MIT

Source 22 files
hooks/register.tsx 5346 lines
1import { atom, read, update } from 'claude-code'
2import type { Chunk, Elements, EngineInterface, Register, RenderSurface, TextHoverProps, Timer, ToolGroupCall, TurnStepResult, UiPressArgument } from 'claude-code'
3
4import type { ActivityKind, ActivityLog, ActivityState, TurnStats, AgentDetail, AgentRecord, CommentDraft, LineComment, DiffFilter, DiffScope, DiffView, FileDiff, OpenedGaps, ImageInfo, PrCheck, PrInfo, PrState, PrThread, RepoInfo, RunCall, Runs, AskState, CommitInfo, FoldedPane, Graphics, SessionEdit, SessionEntry, LiveSession, PreviewFile, Surface, TaskItem, TurnCard, TurnEdit, UsageBreakdown, UsageInfo } from '../types'
5import { CORNER_SIZE, IMAGE_TOKEN, TMUX_GRAPHICS_FORMAT, cornerPixels, graphicsOf, herdrGraphicsOn, imageNumber, pngSize, thumbnailSize, type Corner } from './images'
6import { cellWidth, parseBlocks, renderMarkdown } from './markdown'
7import { blockHeight, diffBlock, diffBlocks, diffPalette, diffRows, gutterWidth, isTruecolor, openGaps, parseHunks, patchBlocks, untab, windowPlan } from './diffview'
8import type { DiffBlock, DiffLine, DiffPalette, DiffRow, Gap } from './diffview'
9import { commentContext, draftKey, lineRef, linesIn, pressLine, rangeLabel, rangeOf, rowOf } from './comments'
10import type { LinePress } from './comments'
11import { agentOf, computeRuns, isAgentTool, isPlanTool, placeCall, planOf, withPredicted } from './runs'
12import type { PredictedCall, RunCursor } from './runs'
13import { activityOf, agentDetailOf, applyNotices, backgroundTaskOf, dismissAgents, isLive, mergeAgents, modelLabel, orderAgents, outputFileOf, parseNotices, stepTokens, tailOf } from './agents'
14import { ago, clip, filterSessions, groupSessions, herdrPaneOf, isGroupFolded, liveSessionsOf, numbered, sessionOf } from './sessions'
15import { answerOf, numberProblem, registerAsk } from './ask'
16import type { AskReply } from './ask'
17import { gather, gatheredLines } from './gather'
18import { computeTasks } from './tasks'
19import { KIND_GLYPH, LOG_EVENTS, NOW_AFTER_MS, PROC_DEPTH, PROC_POLL_MS, QUIET_AFTER_MS, callProcesses, childPids, clipWidth, clockOf, etimesOf, flowRows, ioBytes, isCallRoot, kindOf, laneSegments, procView, sayStrip, statPid, statRow, stepStrip, turnNarration, uptimeTicks } from './activity'
20import type { FlowRow, LaneSegment, ProcRow, StripPart } from './activity'
21import type { ProcSample } from './activity'
22import { OMARCHY_COLORS, parseSurface } from './theme'
23import { limitName, contextChipMode, meterBar, meterLevel, resetIn, ring, showsChip, toBreakdown, toUsage } from './usage'
24import type { ContextChipMode } from './usage'
25import { PR_FIELDS, THREADS_QUERY, checkPrompt, checkSummary, isLocalFailure, jobState, mergeAction, mergeLevel, mergeName, prChipParts, prNumber, prRef, prRepo, reviewName, shortStat, threadPrompt, toDiscussions, toJobs, toMr, toPr, toThreads } from './pr'
26import type { MergeAction, MergeResult, Ran } from './pr'
27import { LOG_FORMAT, MAX_COMMITS, SCOPES, baseCandidates, branchChoices, matchesPath, parseCommits, scopeLabel, scopeOf } from './gitview'
28import { T, currentLang, langFromConfig, langSetting, setLang, type Lang } from './i18n'
29import { previewHtml } from './preview-html'
30import { PREVIEW_PANE, PREVIEW_ROOM, PREVIEW_TOOL, fileName, isMarkdown, isPrivate, previewOf, previewTool } from './preview'
31
32export { cellWidth } from './markdown'
33
34// 데스크톱 앱 CDS 토큰의 역할을 엔진 테마 키에 대응시킨다.
35// hex 를 박으면 터미널 테마(밝음/어두움)와 어긋나므로, 사용자의 테마를 따르는 키만 쓴다.
36const COLORS = {
37  text: 'text',
38  muted: 'inactive',
39  border: 'subtle',
40  clay: 'claude',
41  accent: 'claude',
42  link: 'suggestion',
43  code: 'error',
44  success: 'success',
45  danger: 'error',
46  warning: 'warning',
47} as const
48
49const PANE = 'desk-diff'
50const SESSIONS_PANE = 'desk-sessions'
51const CONTEXT_PANE = 'desk-context'
52const PR_PANE = 'desk-pr'
53const AGENTS_PANE = 'desk-tasks'
54const ACTIVITY_PANE = 'desk-activity'
55const DESK_PANES = new Set([PANE, SESSIONS_PANE, CONTEXT_PANE, PR_PANE, AGENTS_PANE, PREVIEW_PANE, ACTIVITY_PANE])
56// /desk-tasks 끝남 묶음을 접었는지(open 상태의 한 키).
57const DONE_FOLDED = 'tasks:doneFolded'
58const PER_GROUP = 8
59// diff 줄 댓글 칸 높이(쓰는 동안만 끼는 행), 질문 카드 직접 입력칸이 자랄 수 있는 줄 수.
60const COMMENT_ROWS = 3
61const ASK_TEXT_ROWS = 4
62
63const open = atom({ plugin: 'desk-look', key: 'open' } as const, {} as Record<string, boolean>)
64const diff = atom({ plugin: 'desk-look', key: 'diff' } as const, [] as FileDiff[])
65const repo = atom({ plugin: 'desk-look', key: 'repo' } as const, null as RepoInfo | null)
66const surface = atom({ plugin: 'desk-look', key: 'surface' } as const, null as Surface | null)
67const runs = atom({ plugin: 'desk-look', key: 'runs' } as const, { firstOf: {}, calls: {} } as Runs)
68const images = atom({ plugin: 'desk-look', key: 'images' } as const, {} as Record<string, ImageInfo>)
69const graphics = atom({ plugin: 'desk-look', key: 'graphics' } as const, null as Graphics)
70const pendingEdits = atom({ plugin: 'desk-look', key: 'pendingEdits' } as const, [] as TurnEdit[])
71const turnCards = atom({ plugin: 'desk-look', key: 'turnCards' } as const, [] as TurnCard[])
72// /desk-diff 패널 창 위치: ui.scroll 이 알려 준 첫 행과 보이는 행 수. 보이는 곳만 그리는 데 쓴다.
73const diffWindow = atom({ plugin: 'desk-look', key: 'diffWindow' } as const, { offset: 0, bodyRows: 0 })
74// 미리보기 패널에 열린 문서, 그리고 이번 턴에 Write 로 쓴 문서(마지막 것이 턴 끝에 열린다).
75const previewFile = atom({ plugin: 'desk-look', key: 'preview' } as const, null as PreviewFile | null)
76const previewWritten = atom({ plugin: 'desk-look', key: 'previewWritten' } as const, null as string | null)
77const sessions = atom({ plugin: 'desk-look', key: 'sessions' } as const, [] as SessionEntry[])
78const sessionQuery = atom({ plugin: 'desk-look', key: 'sessionQuery' } as const, '')
79const liveSessions = atom({ plugin: 'desk-look', key: 'liveSessions' } as const, {} as Record<string, LiveSession>)
80const turnStartedAt = atom({ plugin: 'desk-look', key: 'turnStartedAt' } as const, null as number | null)
81// 진행 띠를 턴이 끝난 뒤에도 남겨 둔 동안, 그 턴이 끝난 시각. 닫거나(✕) bandAfterTurn 시간이 지나거나 새 턴이 시작되면 비운다.
82const bandDoneAt = atom({ plugin: 'desk-look', key: 'bandDoneAt' } as const, null as number | null)
83// 질문 카드 상태. ask.tsx 의 것과 같은 키다(상태 원본은 파일마다 선언해야 한다).
84const asking = atom({ plugin: 'desk-look', key: 'ask' } as const, null as AskState | null)
85const promptOrigin = atom({ plugin: 'desk-look', key: 'promptOrigin' } as const, null as 'composer' | 'bridge' | null)
86const tasks = atom({ plugin: 'desk-look', key: 'tasks' } as const, [] as TaskItem[])
87const tick = atom({ plugin: 'desk-look', key: 'tick' } as const, 0)
88const IDLE_ACTIVITY: ActivityState = { calls: [], say: null, idleSince: null, proc: null, taskSince: {}, commands: 0, failed: 0, agents: 0 }
89const turnActivity = atom({ plugin: 'desk-look', key: 'activity' } as const, IDLE_ACTIVITY)
90const activityLog = atom({ plugin: 'desk-look', key: 'activityLog' } as const, null as ActivityLog | null)
91// /desk-activity 패널을 다시 그리게 하는 시계(ms). 패널이 그려지고 무언가 돌 때만 ACTIVITY_TICK 마다 간다.
92const activityClock = atom({ plugin: 'desk-look', key: 'activityClock' } as const, 0)
93const usage = atom({ plugin: 'desk-look', key: 'usage' } as const, null as UsageInfo | null)
94const usageBreakdown = atom({ plugin: 'desk-look', key: 'usageBreakdown' } as const, null as UsageBreakdown | null)
95const pr = atom({ plugin: 'desk-look', key: 'pr' } as const, null as PrState | null)
96// diff 줄 댓글: 쓰는 중인 것(고른 줄 범위)과 다음 프롬프트에 붙일 것. 쓰던 글은 draftText 에 둔다:
97// atom 에 두면 글자마다 diff 패널 전체를 다시 그린다. 패널이 다시 그려질 때 입력칸 값으로 돌려준다.
98const commentDraft = atom({ plugin: 'desk-look', key: 'commentDraft' } as const, null as CommentDraft | null)
99const lineComments = atom({ plugin: 'desk-look', key: 'lineComments' } as const, [] as LineComment[])
100let draftText = ''
101// 입력칸 키 차례: 지우기를 누르면 늘려 빈 칸을 새로 그린다.
102let draftRound = 0
103const draftInputKey = (draft: CommentDraft) => `${draftKey(draft)}-${draftRound}`
104// 패널마다 마지막 스크롤 위치(접을 때 적어 둔다)와, 다시 편 뒤 첫 스크롤에 되살릴 위치.
105const paneOffsets = new Map<string, number>()
106const restoreOffsets = new Map<string, number>()
107// diff 패널이 마지막으로 그릴 때 본 접기 상태. 펴기 직후 스크롤은 펴진 그림이 그려진 뒤에 한다.
108let diffDrawnFolds: Record<string, boolean> = {}
109let commentSeq = 0
110const diffView = atom({ plugin: 'desk-look', key: 'diffView' } as const, {
111  scope: 'uncommitted',
112  base: null,
113  baseRef: null,
114  bases: null,
115  files: [],
116  commits: [],
117  commitFiles: {},
118} as DiffView)
119const diffGaps = atom({ plugin: 'desk-look', key: 'diffGaps' } as const, {} as Record<string, OpenedGaps>)
120const diffFilter = atom({ plugin: 'desk-look', key: 'diffFilter' } as const, { isOpen: false, query: '' } as DiffFilter)
121// diff 패널이 마지막으로 그린 파일 머리 띠(위에서부터): 접기 id 와 첫 행. n·p 이동에 쓴다.
122let diffHeads: { id: string; top: number }[] = []
123// n·p·머리 띠 누름이 마지막으로 스크롤해 간 파일. 사람이 창을 옮기면 잊는다.
124let diffCursor: string | null = null
125
126const agents = atom({ plugin: 'desk-look', key: 'agents' } as const, {} as Record<string, AgentRecord>)
127const agentView = atom({ plugin: 'desk-look', key: 'agentView' } as const, null as string | null)
128const agentDetail = atom({ plugin: 'desk-look', key: 'agentDetail' } as const, null as AgentDetail | null)
129const agentClock = atom({ plugin: 'desk-look', key: 'agentClock' } as const, 0)
130const taskOutput = atom({ plugin: 'desk-look', key: 'taskOutput' } as const, null as { id: string; text: string | null } | null)
131// /desk-fold 로 접어 둔 패널. 펴면 비운다. 접은 동안은 내 패널이 없었어도 빈 목록이다(toggleFold).
132const folded = atom({ plugin: 'desk-look', key: 'folded' } as const, null as FoldedPane[] | null)
133// 지금 화면 언어. desk-asana·desk-slack 이 이 값을 따른다.
134const lang = atom({ plugin: 'desk-look', key: 'lang' } as const, 'en' as Lang)
135// 같은 마켓의 desk-asana·desk-slack 이 쓰는 값(읽기만): 접어 둔 패널, 이 세션에 떠 있는지, 안 읽은 Slack 메시지 수.
136const asanaFolded = atom({ plugin: 'desk-asana', key: 'folded' } as const, null as FoldedPane[] | null)
137const slackFolded = atom({ plugin: 'desk-slack', key: 'folded' } as const, null as FoldedPane[] | null)
138const asanaReady = atom({ plugin: 'desk-asana', key: 'ready' } as const, false)
139const slackReady = atom({ plugin: 'desk-slack', key: 'ready' } as const, false)
140const slackUnread = atom({ plugin: 'desk-slack', key: 'unread' } as const, 0)
141// desk-asana·desk-slack 의 패널이 지금 열려 있는지(그쪽이 ui.open·ui.close 로 맞춘다). /desk-fold 가 접을지 펼지 고른다.
142const asanaShown = atom({ plugin: 'desk-asana', key: 'shown' } as const, false)
143const slackShown = atom({ plugin: 'desk-slack', key: 'shown' } as const, false)
144
145// 스피너 시계: 엔진은 모드가 바뀔 때만 Spinner 를 다시 그리므로 직접 tick 을 올려 다시 그리게 한다.
146// 스피너가 사라지면(마지막으로 그린 지 2초가 지나면) 스스로 멈춘다.
147const SPINNER_TICK = 500
148// 답 글 블록째 보여주기: 마지막 블록을 내보낸 뒤 턴을 끝내기 전에 기다리는 시간(엔진의 글 묶음 100ms 보다 길게).
149const GATHER_SETTLE_MS = 150
150// /desk-update 가 답한 뒤 /reload-plugins 를 부르기까지(답 줄이 먼저 찍히게).
151const RELOAD_AFTER_MS = 300
152let ticker: Timer | null = null
153const THEME_POLL = 3000
154let themeWatch: Timer | null = null
155let spinnerSeen = 0
156let spinnerFallbackStart = 0
157
158// 스트림이 막 엔진에 넘긴 도구 호출: 기록(session.append)에 나오기 전까지 묶음에 미리 넣어 둔다.
159let runCursor: RunCursor = null
160let predicted: PredictedCall[] = []
161// 진행 띠가 Bash 가 띄운 프로세스를 읽는 시계와 직전 표본. claudePid 는 /proc/self/stat 에서 한 번 읽고,
162// /proc 이 없으면(macOS) null 로 두어 다시 읽지 않는다.
163let procTimer: Timer | null = null
164let procSample: ProcSample | null = null
165let claudePid: number | null | undefined
166// 시작했지만 아직 메인 작업(도구 호출·호출 앞 설명)이 없는 턴의 시작 시각. /desk-activity 기록은 첫 메인 작업이 올 때
167// 이 턴으로 바꾼다: 그 전에는 지난 턴을 그대로 보이고, 글로만 답한 턴이나 백그라운드 끝남 알림 턴은 기록을 건드리지 않는다.
168let pendingLogStart: number | null = null
169// 패널 시계: 막대와 시간은 2초 단위면 충분하다(스피너처럼 초당 두 번 그리면 턴 중 비용이 크게 는다).
170const ACTIVITY_TICK = 2000
171let activityTimer: Timer | null = null
172let activitySeen = 0
173// 엔진이 백그라운드 안내("(ctrl+b to run in background)")를 띄운 호출과 그 글. 스피너 줄 끝에 단다.
174const backgroundHints = new Map<string, string>()
175
176const FILE_EDITING = new Set(['Edit', 'MultiEdit', 'Write', 'NotebookEdit'])
177const CARD_ROWS = 3
178// 턴 기록은 최근 60턴, 복사할 답변은 턴마다 5만 자까지만 둔다.
179const TURN_CARDS = 60
180const MAX_COPY = 50_000
181
182// 같은 파일을 여러 번 고치면 한 줄로 합친다.
183export function mergeEdit(list: TurnEdit[], edit: TurnEdit): TurnEdit[] {
184  const index = list.findIndex(item => item.path === edit.path)
185  if (index === -1) return [...list, edit]
186  return list.map((item, at) =>
187    at === index ? { ...item, added: item.added + edit.added, removed: item.removed + edit.removed } : item,
188  )
189}
190
191
192const lastLine = (text: string) => text.trim().split('\n').pop() ?? ''
193
194// `claude plugin update --json` 의 결과 한 줄을 사람에게 보일 문장으로.
195function updateResult(stdout: string): { outcome?: string; updateOutcome?: string; oldVersion?: string; newVersion?: string; message?: string } | null {
196  try {
197    return JSON.parse(lastLine(stdout))
198  } catch {
199    return null
200  }
201}
202
203// 새 버전을 받았는지: 그때만 플러그인을 다시 불러온다.
204export function isUpdated(exitCode: number, stdout: string): boolean {
205  const result = updateResult(stdout)
206  return exitCode === 0 && result?.outcome === 'ok' && result.updateOutcome !== 'up_to_date'
207}
208
209export function updateMessage(exitCode: number, stdout: string, stderr: string): string {
210  const result = updateResult(stdout)
211  if (exitCode !== 0 || result?.outcome !== 'ok') return T.updateFailed(result?.message ?? lastLine(stderr || stdout))
212  if (result.updateOutcome === 'up_to_date') return T.updateLatest(result.newVersion ?? '')
213  return T.updateDone(result.oldVersion ?? '', result.newVersion ?? '')
214}
215
216// desk-asana·desk-slack 을 올렸을 때만 한 줄. 최신이거나 설치하지 않아 실패했으면 null.
217export function siblingUpdate(name: string, exitCode: number, stdout: string): string | null {
218  if (!isUpdated(exitCode, stdout)) return null
219  const result = updateResult(stdout)
220  return T.siblingUpdated(name, result?.oldVersion ?? '', result?.newVersion ?? '')
221}
222
223// 세션 편집: 파일별로 합치고 헌크는 편집 순서대로 붙인다. 최근 파일 SESSION_FILES 개, 파일마다 헌크 SESSION_PATCHES 개까지.
224const SESSION_FILES = 50
225const SESSION_PATCHES = 20
226
227export function mergeSessionEdit(list: SessionEdit[], edit: SessionEdit): SessionEdit[] {
228  const old = list.find(item => item.path === edit.path)
229  const merged = old
230    ? { path: edit.path, added: old.added + edit.added, removed: old.removed + edit.removed, patches: [...old.patches, ...edit.patches].slice(-SESSION_PATCHES) }
231    : edit
232  return [...list.filter(item => item.path !== edit.path), merged].slice(-SESSION_FILES)
233}
234
235// 대화 기록(runs)의 성공한 편집 도구 호출을 파일별로 모은다. 기록에서 다시 계산하므로 재시작·resume 뒤에도 남는다.
236export function sessionEditsOf(state: Runs): SessionEdit[] {
237  let list: SessionEdit[] = []
238  for (const call of Object.values(state.calls).flat()) {
239    if (!FILE_EDITING.has(call.tool) || call.isRunning) continue
240    const fields = fieldsOf(call.input)
241    const path = stringField(fields, 'file_path') ?? stringField(fields, 'notebook_path')
242    const stat = diffStat(call)
243    if (path && stat) list = mergeSessionEdit(list, { path, ...stat, patches: editPatches(call.tool, call.input, call.output) })
244  }
245  return list
246}
247
248// diff 패널에 git 대신 세션 기록으로 보일 편집: git diff 가 잡지 못하는 저장소 밖(또는 저장소가 아닌 곳) 파일과
249// 저장소 안이지만 git 이 무시하는 파일(.gitignore). 그 밖의 저장소 안 파일은 git 이 정본이다(커밋했으면 패널에서 빠지는 게 맞다).
250export function outsideEdits(edits: ReadonlyArray<SessionEdit>, info: RepoInfo | null): SessionEdit[] {
251  if (info?.isRepo !== true) return [...edits]
252  const root = info.root
253  const ignored = new Set(info.ignored ?? [])
254  return root ? edits.filter(edit => !edit.path.startsWith(`${root}/`) || ignored.has(edit.path)) : []
255}
256
257// 소요 시간 줄과 턴 기록을 durationMs 로 짝짓는다. 둘이 같은 값을 재지만 반올림 차이를 1초까지 봐준다.
258export function cardFor(cards: ReadonlyArray<TurnCard>, durationMs: number): TurnCard | undefined {
259  let best: TurnCard | undefined
260  for (const card of cards) {
261    const gap = Math.abs(card.durationMs - durationMs)
262    if (gap <= 1000 && (best === undefined || gap < Math.abs(best.durationMs - durationMs))) best = card
263  }
264  return best
265}
266
267const EDITING_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit', 'MultiEdit', 'Bash'])
268
269type Call = Pick<ToolGroupCall, 'tool' | 'input' | 'isRunning' | 'isErrored' | 'isInterrupted' | 'output'>
270
271type Category = 'command' | 'read' | 'edit' | 'create' | 'search' | 'web' | 'agent' | 'todo' | 'ask' | 'other'
272
273const CATEGORY_OF: Record<string, Category> = {
274  Bash: 'command',
275  BashOutput: 'command',
276  KillShell: 'command',
277  PowerShell: 'command',
278  Read: 'read',
279  NotebookRead: 'read',
280  Edit: 'edit',
281  MultiEdit: 'edit',
282  NotebookEdit: 'edit',
283  Write: 'create',
284  Grep: 'search',
285  Glob: 'search',
286  LS: 'search',
287  ToolSearch: 'search',
288  WebFetch: 'web',
289  WebSearch: 'web',
290  Agent: 'agent',
291  Task: 'agent',
292  TodoWrite: 'todo',
293  TaskCreate: 'todo',
294  TaskUpdate: 'todo',
295  TaskList: 'todo',
296  AskUserQuestion: 'ask',
297}
298
299// 데스크톱의 "Ran 2 commands, created a file, edited 3 files, and 3 more actions" 문구.
300const PHRASES: Record<Category, [string, (count: number) => string]> = {
301  command: ['ran a command', count => `ran ${count} commands`],
302  read: ['read a file', count => `read ${count} files`],
303  edit: ['edited a file', count => `edited ${count} files`],
304  create: ['created a file', count => `created ${count} files`],
305  search: ['searched', count => `searched ${count} times`],
306  web: ['fetched a page', count => `fetched ${count} pages`],
307  agent: ['ran an agent', count => `ran ${count} agents`],
308  todo: ['updated todos', () => 'updated todos'],
309  ask: ['asked a question', count => `asked ${count} questions`],
310  other: ['used a tool', count => `used ${count} tools`],
311}
312
313const VERB: Record<Category, string> = {
314  command: 'Ran',
315  read: 'Read',
316  edit: 'Edited',
317  create: 'Created',
318  search: 'Searched',
319  web: 'Fetched',
320  agent: 'Agent',
321  todo: 'Updated todos',
322  ask: 'Asked',
323  other: 'Used',
324}
325
326const categoryOf = (tool: string): Category => CATEGORY_OF[tool] ?? 'other'
327
328export function describeCalls(calls: ReadonlyArray<Call>): string {
329  const counts = new Map<Category, number>()
330  for (const call of calls) {
331    const category = categoryOf(call.tool)
332    counts.set(category, (counts.get(category) ?? 0) + 1)
333  }
334  const entries = [...counts]
335  const phrase = ([category, count]: [Category, number]) =>
336    count === 1 ? PHRASES[category][0] : PHRASES[category][1](count)
337  const shown = entries.slice(0, 3).map(phrase)
338  const rest = entries.slice(3).reduce((sum, [, count]) => sum + count, 0)
339  const text = rest > 0 ? `${shown.join(', ')}, and ${rest} more action${rest === 1 ? '' : 's'}` : shown.join(', ')
340  const failed = calls.filter(call => call.isErrored).length
341  return text.charAt(0).toUpperCase() + text.slice(1) + (failed > 0 ? ` (${failed} failed)` : '')
342}
343
344const fieldsOf = (input: unknown): Record<string, unknown> =>
345  typeof input === 'object' && input !== null ? (input as Record<string, unknown>) : {}
346
347const stringField = (fields: Record<string, unknown>, key: string) =>
348  typeof fields[key] === 'string' ? (fields[key] as string) : undefined
349
350// 동사 옆에 붙는 회색 대상: 파일명, 명령, 패턴, URL.
351export function summarize(tool: string, input: unknown): string {
352  const fields = fieldsOf(input)
353  const path = stringField(fields, 'file_path') ?? stringField(fields, 'notebook_path') ?? stringField(fields, 'path')
354  const questions = Array.isArray(fields.questions) ? fields.questions.map(fieldsOf) : []
355  const summary =
356    (tool === 'Bash' ? stringField(fields, 'command') : undefined) ??
357    (tool === 'AskUserQuestion' ? stringField(questions[0] ?? {}, 'question') : undefined) ??
358    (path ? path.split('/').pop() : undefined) ??
359    stringField(fields, 'pattern') ??
360    stringField(fields, 'url') ??
361    stringField(fields, 'query') ??
362    stringField(fields, 'description') ??
363    stringField(fields, 'prompt') ??
364    Object.values(fields).find((value): value is string => typeof value === 'string') ??
365    ''
366  return summary.split('\n')[0] ?? ''
367}
368
369// 질문 도구의 답: 결과의 answers 값들. 없으면 null.
370export function askAnswer(output: unknown): string | null {
371  let value = output
372  if (typeof value === 'string') {
373    try {
374      value = JSON.parse(value)
375    } catch {
376      return null
377    }
378  }
379  const answers = fieldsOf(fieldsOf(value).answers)
380  const list = Object.values(answers).filter((answer): answer is string => typeof answer === 'string' && answer !== '')
381  return list.length > 0 ? list.join(' · ') : null
382}
383
384function verbOf(tool: string): string {
385  if (tool === PREVIEW_TOOL) return 'Previewed'
386  const category = categoryOf(tool)
387  if (category !== 'other') return VERB[category]
388  // mcp__server__tool → tool
389  return `Used ${tool.startsWith('mcp__') ? (tool.split('__').pop() ?? tool) : tool}`
390}
391
392// 끝 줄바꿈은 줄을 하나 더 만들지 않는다('a\nb\n' 은 2줄).
393const lineCount = (text: unknown) => (typeof text === 'string' ? linesOf(text.replace(/\n$/, '')).length : 0)
394
395// 앞뒤로 같은 줄 수. 편집은 old_string 에 문맥 줄을 함께 넣으니 그 줄은 바뀐 것으로 치지 않는다.
396function commonEnds(before: string[], after: string[]): { head: number; tail: number } {
397  let head = 0
398  while (head < before.length && head < after.length && before[head] === after[head]) head++
399  let tail = 0
400  while (
401    tail < before.length - head &&
402    tail < after.length - head &&
403    before[before.length - 1 - tail] === after[after.length - 1 - tail]
404  )
405    tail++
406  return { head, tail }
407}
408
409const linesOf = (text: string) => (text === '' ? [] : text.split('\n'))
410
411// Edit 의 old/new 는 바꾼 줄 앞뒤 문맥 줄을 함께 담는다. 앞뒤 공통 줄을 걷어내고 남은 줄만 센다.
412export function lineChange(oldText: string, newText: string): { added: number; removed: number } {
413  const before = linesOf(oldText)
414  const after = linesOf(newText)
415  const { head, tail } = commonEnds(before, after)
416  return { added: after.length - head - tail, removed: before.length - head - tail }
417}
418
419// 편집 도구의 +/− 줄 수: 데스크톱의 초록·빨강 칩.
420export function diffStat(call: Call): { added: number; removed: number } | null {
421  if (call.isErrored || call.isInterrupted) return null
422  const fields = fieldsOf(call.input)
423  switch (call.tool) {
424    case 'Edit':
425      return lineChange(stringField(fields, 'old_string') ?? '', stringField(fields, 'new_string') ?? '')
426    case 'MultiEdit': {
427      const edits = Array.isArray(fields.edits) ? fields.edits.map(fieldsOf) : []
428      const changes = edits.map(edit => lineChange(stringField(edit, 'old_string') ?? '', stringField(edit, 'new_string') ?? ''))
429      return {
430        added: changes.reduce((sum, change) => sum + change.added, 0),
431        removed: changes.reduce((sum, change) => sum + change.removed, 0),
432      }
433    }
434    case 'Write': {
435      // 있던 파일을 덮어쓰면 결과에 헌크가 온다. 새 파일은 헌크가 비어 내용 줄 수를 쓴다.
436      const hunks = (call.output as { structuredPatch?: unknown } | null | undefined)?.structuredPatch
437      if (Array.isArray(hunks) && hunks.length > 0) {
438        const lines = hunks.flatMap(hunk => (hunk as { lines?: unknown }).lines).filter((line): line is string => typeof line === 'string')
439        return { added: lines.filter(line => line.startsWith('+')).length, removed: lines.filter(line => line.startsWith('-')).length }
440      }
441      return { added: lineCount(fields.content), removed: 0 }
442    }
443    case 'NotebookEdit':
444      return { added: lineCount(fields.new_source), removed: 0 }
445    default:
446      return null
447  }
448}
449
450export function outputText(output: unknown): string {
451  if (output === undefined || output === null) return ''
452  if (typeof output === 'string') return output
453  const fields = fieldsOf(output)
454  const stdout = stringField(fields, 'stdout')
455  if (stdout !== undefined) return [stdout, stringField(fields, 'stderr') ?? ''].filter(Boolean).join('\n')
456  const file = fieldsOf(fields.file)
457  const content = stringField(file, 'content') ?? stringField(fields, 'content')
458  if (content !== undefined) return content
459  try {
460    return JSON.stringify(output, null, 2)
461  } catch {
462    return String(output)
463  }
464}
465
466function cap(text: string, lines: number): string {
467  const all = text.replace(/\s+$/, '').split('\n')
468  return all.length <= lines ? all.join('\n') : `${all.slice(0, lines).join('\n')}\n${T.moreLines(all.length - lines)}`
469}
470
471// Edit·MultiEdit 결과의 structuredPatch: 파일 기준 줄 번호와 앞뒤 문맥이 붙은 헌크. 없으면 null.
472export function patchOf(output: unknown): string | null {
473  const hunks = (output as { structuredPatch?: unknown } | null | undefined)?.structuredPatch
474  if (!Array.isArray(hunks) || hunks.length === 0) return null
475  return hunks
476    .map(hunk => {
477      const part = hunk as { oldStart: number; oldLines: number; newStart: number; newLines: number; lines: string[] }
478      return [`@@ -${part.oldStart},${part.oldLines} +${part.newStart},${part.newLines} @@`, ...part.lines].join('\n')
479    })
480    .join('\n')
481}
482
483// 성공한 편집 도구 호출의 헌크들: 결과의 structuredPatch, 없으면 입력에서 만든다(새로 쓴 파일은 전부 +).
484export function editPatches(tool: string, input: unknown, result: unknown): string[] {
485  const fromResult = patchOf(result)
486  if (fromResult) return [fromResult]
487  const fields = fieldsOf(input)
488  switch (tool) {
489    case 'Edit':
490      return [editHunk(stringField(fields, 'old_string') ?? '', stringField(fields, 'new_string') ?? '')]
491    case 'MultiEdit':
492      return (Array.isArray(fields.edits) ? fields.edits.map(fieldsOf) : []).map(edit =>
493        editHunk(stringField(edit, 'old_string') ?? '', stringField(edit, 'new_string') ?? ''),
494      )
495    case 'Write': {
496      const lines = linesOf((stringField(fields, 'content') ?? '').replace(/\n$/, ''))
497      return lines.length === 0 ? [] : [[`@@ -0,0 +1,${lines.length} @@`, ...lines.map(line => `+${line}`)].join('\n')]
498    }
499    default:
500      return []
501  }
502}
503
504// 편집 하나를 diff 헌크로(결과에 헌크가 없을 때): 바뀐 줄만 −/+, 앞뒤 같은 줄은 문맥으로 두 줄까지.
505export function editHunk(oldText: string, newText: string, context = 2): string {
506  const before = linesOf(oldText)
507  const after = linesOf(newText)
508  const { head, tail } = commonEnds(before, after)
509  const lead = before.slice(Math.max(0, head - context), head)
510  const trail = before.slice(before.length - tail, before.length - tail + context)
511  const removed = before.slice(head, before.length - tail)
512  const added = after.slice(head, after.length - tail)
513  const start = head - lead.length + 1
514  return [
515    `@@ -${start},${lead.length + removed.length + trail.length} +${start},${lead.length + added.length + trail.length} @@`,
516    ...lead.map(line => ` ${line}`),
517    ...removed.map(line => `-${line}`),
518    ...added.map(line => `+${line}`),
519    ...trail.map(line => ` ${line}`),
520  ].join('\n')
521}
522
523// 패널이 그릴 diff 만 상태에 둔다. 엔진은 atom 값 하나를 4 MiB 글자로 묶어 넘으면 $.state.set 이 던지고,
524// 한 번 그리는 글자도 10만 자에서 자른다. 한 줄이 아주 긴 파일(빌드 결과물·minified)이나 아주 큰 파일은 내용을
525// 비우고 +/− 수만 남긴다. clara-apm 의 3.8 MB 번들 커밋이 브랜치 diff 와 함께 7.6 M 자가 되어 커밋 줄이 안 펴졌다.
526const PATCH_LINE_MAX = 2000
527const PATCH_MAX = 200_000
528// atom 하나에 넣는 diff 내용의 합계. 4 MiB 에서 경로·커밋 목록 몫을 남긴다.
529const PATCHES_MAX = 3_000_000
530
531// `git diff` 출력을 파일 단위로 나눈다. Code format: 'diff' 는 @@ 헌크부터 받는다.
532export function parseDiff(text: string, isNew = false): FileDiff[] {
533  const files: FileDiff[] = []
534  for (const chunk of text.split(/^diff --git /m).slice(1)) {
535    const lines = chunk.split('\n')
536    const header = lines[0] ?? ''
537    const path = header.replace(/^a\/.* b\/(.*)$/, '$1')
538    const firstHunk = lines.findIndex(line => line.startsWith('@@'))
539    const hunks = firstHunk === -1 ? [] : lines.slice(firstHunk)
540    const patch = hunks.join('\n').trimEnd()
541    const file = {
542      path,
543      added: hunks.filter(line => line.startsWith('+')).length,
544      removed: hunks.filter(line => line.startsWith('-')).length,
545      patch,
546      isNew,
547    }
548    files.push(patch.length > PATCH_MAX || hunks.some(line => line.length > PATCH_LINE_MAX) ? { ...file, patch: '', large: true } : file)
549  }
550  return files
551}
552
553// 한 atom 에 함께 들어갈 diff 묶음들을 합계 안으로 줄인다: 큰 파일부터 내용을 비운다. 묶음 모양은 그대로.
554export function fitDiffs(groups: FileDiff[][], room = PATCHES_MAX): FileDiff[][] {
555  const sized = groups.flat().map(file => ({ file, size: JSON.stringify(file.patch).length }))
556  let total = sized.reduce((sum, entry) => sum + entry.size, 0)
557  const dropped = new Set<FileDiff>()
558  for (const entry of sized.sort((a, b) => b.size - a.size)) {
559    if (total <= room) break
560    dropped.add(entry.file)
561    total -= entry.size
562  }
563  return dropped.size === 0 ? groups : groups.map(files => files.map(file => (dropped.has(file) ? { ...file, patch: '', large: true } : file)))
564}
565
566// 브랜치 전체와 펼친 커밋들은 diffView 한 atom 에 산다.
567export function fitView(view: DiffView): DiffView {
568  const shas = Object.keys(view.commitFiles)
569  const [files = [], ...commits] = fitDiffs([view.files, ...shas.map(sha => view.commitFiles[sha] ?? [])])
570  return { ...view, files, commitFiles: Object.fromEntries(shas.map((sha, index) => [sha, commits[index] ?? []])) }
571}
572
573// 사용자 git 설정(diff.mnemonicPrefix·noprefix)과 상관없이 머리말을 a/ b/ 로 고정해 경로를 읽는다.
574// git 을 부르는 자리마다 명령 전체를 고정 글자로 쓴다(디렉터리 검사가 무엇을 실행하는지 끝까지 읽게). diff 는 늘
575// --no-color --no-ext-diff --src-prefix=a/ --dst-prefix=b/ 로 같은 모양을 받는다. 길이가 변하는 목록(경로·커밋)은 stdin 으로.
576
577// update 는 fn 이 같은 값을 돌려줘도 늘 써서 판을 올리고, 그 atom 을 읽는 그림을 모두 다시 그린다.
578// 다시 읽어 온 값은 먼저 read 로 견주고 바뀔 때만 쓴다(대기 중 테마를 3초마다 읽을 때 화면 전체를 다시 그리던 것).
579// 엔진 검사가 read·update 의 atom 을 호출 자리에서 찾아서 함수로 묶지 못한다.
580const sameJson = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
581
582// 컨텍스트 칩의 숫자: 인자 없는 usage() 는 상태 줄의 값이라 공짜다. 턴이 끝날 때마다 다시 읽는다.
583async function refreshUsage($: EngineInterface) {
584  const [raw, now] = await Promise.all([$.session.usage(), $.clock.now()])
585  const next = toUsage(raw, now)
586  if (!sameJson({ ...(await read($, usage)), at: 0 }, { ...next, at: 0 })) await update($, usage, () => next)
587}
588
589// 패널을 열 때만 항목별 내역을 계산한다. summary 는 로컬 추정이라 API 요청이 없다(full 은 도구마다 요청).
590async function refreshBreakdown($: EngineInterface) {
591  const [raw, now] = await Promise.all([$.session.usage({ breakdown: 'summary' }), $.clock.now()])
592  await update($, usage, () => toUsage(raw, now))
593  await update($, usageBreakdown, () => toBreakdown(raw, now))
594}
595
596async function openContext($: EngineInterface) {
597  await refreshBreakdown($).catch(() => undefined)
598  await $.ui.open({ id: CONTEXT_PANE, title: T.paneContext, focus: true })
599}
600
601// 줄 전체가 눌리는 버튼: 라벨 뒤에 칩·흐린 설명(Text)을 함께 넣는다.
602type RowButtonProps = { key: string; dimColor?: boolean; hotkey?: string; hover?: TextHoverProps; onPress: (press: UiPressArgument) => void }
603
604function rowButton(els: Els, props: RowButtonProps, label: string, ...rest: unknown[]) {
605  const { Button } = els
606  const parts = rest.filter(part => part !== null && part !== undefined && part !== false && part !== '')
607  return (
608    <Button plain {...props}>
609      {label}
610      {parts as never}
611    </Button>
612  )
613}
614
615// 아래턱 오른쪽의 "◔ 62%": 링은 단계 색, 칩 전체가 컨텍스트 패널을 여는 버튼.
616function contextMeter(els: Els, $: EngineInterface, info: UsageInfo | null, mode: ContextChipMode) {
617  const percent = info?.percent ?? null
618  if (!showsChip(mode, percent)) return null
619  const { Box, Text, Button } = els
620  const level = meterLevel(percent)
621  const label = `${percent}%`
622  return {
623    width: 2 + cellWidth(label),
624    node: (
625      <Button key="context-chip" plain dimColor={level === 'muted'} onPress={() => void openContext($)}>
626        <Text color={COLORS[level]}>{ring(percent)}</Text>
627        {` ${label}`}
628      </Button>
629    ),
630  }
631}
632
633// 아래턱 오른쪽의 PR 칩 "#12 ✓ 5/5": 누르면 /desk-pr 패널.
634function prChip(els: Els, $: EngineInterface, state: PrState | null) {
635  const info = state?.pr
636  if (!info) return null
637  const { Box, Text, Button } = els
638  const parts = prChipParts(info)
639  const text = parts.map(part => part.text).join(' ')
640  const colored = parts.slice(1).map((part, index) => (
641    <Text key={`pr-part-${index}`} color={COLORS[part.color]}>{` ${part.text}`}</Text>
642  ))
643  return {
644    width: cellWidth(text),
645    node: (
646      <Button key="pr-chip" plain dimColor onPress={() => void openPr($)}>
647        {parts[0]!.text}
648        {colored as never}
649      </Button>
650    ),
651  }
652}
653
654async function refreshDiff($: EngineInterface) {
655  const opts = { timeoutMs: 5000 }
656  const inside = await $.process.run(['git', 'rev-parse', '--is-inside-work-tree'], opts)
657  if (inside.exitCode !== 0) {
658    const cwd = await $.session.cwd()
659    await update($, repo, () => ({ name: cwd.split('/').pop() ?? cwd, branch: null, isRepo: false }))
660    await update($, diff, () => [])
661    return
662  }
663  const [top, branch, tracked, untracked] = await Promise.all([
664    $.process.run(['git', 'rev-parse', '--show-toplevel'], opts),
665    $.process.run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], opts),
666    $.process.run(['git', 'diff', 'HEAD', '--no-color', '--no-ext-diff', '--src-prefix=a/', '--dst-prefix=b/'], opts).then(ran => (ran.exitCode === 0 ? ran : $.process.run(['git', 'diff', '--no-color', '--no-ext-diff', '--src-prefix=a/', '--dst-prefix=b/'], opts))),
667    $.process.run(['git', 'ls-files', '--others', '--exclude-standard'], opts),
668  ])
669  // 새로 만든 파일은 `git diff HEAD` 에 안 잡힌다. 데스크톱처럼 보이도록 최대 20개까지 붙인다.
670  const fresh = untracked.stdout.split('\n').filter(Boolean).slice(0, 20)
671  const freshDiffs = await Promise.all(fresh.map(path => $.process.run(['git', 'diff', '--no-index', '--no-color', '--no-ext-diff', '--src-prefix=a/', '--dst-prefix=b/', '--', '/dev/null', path], opts)))
672  const files = [
673    ...parseDiff(tracked.stdout),
674    ...freshDiffs.flatMap(ran => parseDiff(ran.stdout, true)),
675  ]
676  // 이 세션이 고친 저장소 안 파일 중 git 이 무시하는 것은 git diff·ls-files 어디에도 안 잡힌다. 세션 기록으로 보이게 골라 둔다.
677  const root = top.stdout.trim()
678  const inRepo = root ? sessionEditsOf(await read($, runs)).map(edit => edit.path).filter(path => path.startsWith(`${root}/`)) : []
679  const ignored = inRepo.length ? (await $.process.run(['git', 'check-ignore', '--stdin'], { ...opts, stdin: `${inRepo.join('\n')}\n` })).stdout.split('\n').filter(Boolean) : []
680  await update($, repo, () => ({
681    name: root.split('/').pop() ?? '',
682    branch: branch.exitCode === 0 ? branch.stdout.trim() : null,
683    isRepo: true,
684    root: root || undefined,
685    ignored,
686  }))
687  await update($, diff, () => fitDiffs([files])[0] ?? [])
688}
689
690// diff 패널의 되돌리기: 처음 누르면 5초 동안 확인 상태, 그 안에 한 번 더 누르면 HEAD 로 되돌린다.
691// 커밋하지 않은 변경을 버리는 일이라 두 번 눌러야 하고, git 이 아는 파일만 대상이다(새 파일은 지우게 되므로 없음).
692const REVERT_ARM_MS = 5000
693
694async function revertFile($: EngineInterface, path: string, isArmed: boolean) {
695  const key = `revert:${path}`
696  if (!isArmed) {
697    await update($, open, state => ({ ...state, [key]: true }))
698    $.clock.after(REVERT_ARM_MS, () => void update($, open, state => ({ ...state, [key]: false })))
699    return
700  }
701  await update($, open, state => ({ ...state, [key]: false }))
702  const top = await $.process.run(['git', 'rev-parse', '--show-toplevel'], { timeoutMs: 5000 })
703  const ran = await $.process.run(['git', 'restore', '--source=HEAD', '--staged', '--worktree', '--', path], {
704    cwd: top.stdout.trim() || undefined,
705    timeoutMs: 5000,
706  })
707  $.ui.toast(ran.exitCode === 0 ? T.reverted(path) : T.revertFailed(ran.stderr.trim().split('\n')[0] ?? ''))
708  await refreshDiff($)
709}
710
711// 처음 상태가 펼침인 행(묶음 안의 편집)도 있어서, 지금 보이는 상태를 받아 뒤집는다.
712const toggle = ($: EngineInterface, id: string, shown?: boolean) =>
713  update($, open, state => ({ ...state, [id]: !(state[id] ?? shown ?? false) }))
714
715// 턴 끝 카드의 파일(도구가 준 경로, 보통 절대 경로)이나 /desk-diff 에 준 이름(뒷부분)에 맞는
716// diff 패널 파일(저장소 기준 경로). 절대 경로 쪽은 가장 길게 맞는 것, 이름 쪽은 첫 번째.
717export function matchDiffFile(files: ReadonlyArray<{ path: string }>, path: string): string | null {
718  const whole = files.filter(file => file.path === path || path.endsWith(`/${file.path}`))
719  const best = whole.sort((a, b) => b.path.length - a.path.length)[0]
720  return best?.path ?? files.find(file => file.path.endsWith(`/${path}`))?.path ?? null
721}
722
723// 앞을 줄인다: 경로는 파일 이름 쪽이 중요하다.
724export function clipStart(text: string, width: number): string {
725  if (cellWidth(text) <= width) return text
726  let out = ''
727  for (const ch of [...text].reverse()) {
728    if (cellWidth(ch + out) > width - 1) break
729    out = ch + out
730  }
731  return `…${out}`
732}
733
734// diff 패널에서 세션 기록으로 보이는 파일의 키 앞머리.
735const OUTSIDE = 's:'
736// git 밖 편집 묶음 전체의 접기 키. 파일 접기 키(fold:경로)와 겹치지 않게 따로 둔다.
737const OUTSIDE_GROUP = 'group:outside'
738
739// 데스크톱처럼 턴 끝 카드의 파일을 누르면 diff 패널을 그 파일에서 연다(접혀 있으면 펼쳐서).
740// 문서를 읽어 미리보기 상태에 둔다. 경로는 실제 경로로 바꿔 둬서 나중에 다른 모양의 경로로 온 편집도 같은 문서로 안다.
741// 못 읽으면 던지지 않고 사유를 담는다.
742async function loadPreview($: EngineInterface, asked: string): Promise<PreviewFile> {
743  const path = await $.fs.stat(asked, { resolve: true }).then(
744    stat => stat.realPath ?? asked,
745    () => asked,
746  )
747  const file: PreviewFile = await $.fs.read(path).then(
748    text => ({ path, text }),
749    (error: unknown) => ({ path, text: '', error: error instanceof Error ? error.message : String(error) }),
750  )
751  await update($, previewFile, () => file)
752  return file
753}
754
755async function openPreview($: EngineInterface, path: string, focus = false) {
756  const file = await loadPreview($, path)
757  const opened = await $.ui.open({ id: PREVIEW_PANE, title: fileName(file.path), ...(focus ? { focus: true as const } : {}) })
758  return { file, isPlaced: opened.isPlaced }
759}
760
761// o: 미리보기 문서를 브라우저 창으로. 패널은 터미널의 45%를 넘지 못해 창 전체로 보려면 바깥 창이 필요하다.
762// 엔진 임시 폴더에 HTML 을 쓰고 엔진이 브라우저를 여는 것처럼 xdg-open(없으면 macOS 의 open)으로 연다.
763async function openPreviewInBrowser($: EngineInterface, file: PreviewFile) {
764  const root = await findTempRoot($)
765  if (root === null) return $.ui.toast(T.browserFailed('id -u'))
766  const page = `${root}/desk-look/${fileName(file.path).replace(/\.[^.]+$/, '')}.html`
767  await $.fs.write(page, previewHtml(file.text, file.path))
768  const failed = (error: unknown) => ({ exitCode: 1, stderr: error instanceof Error ? error.message : String(error) })
769  let ran: { exitCode: number; stderr: string }
770  try {
771    ran = await $.process.run(['xdg-open', page], { timeoutMs: 10_000 })
772  } catch {
773    ran = await $.process.run(['open', page], { timeoutMs: 10_000 }).catch(failed)
774  }
775  $.ui.toast(ran.exitCode === 0 ? T.browserOpened(page) : T.browserFailed(ran.stderr.trim() || `exit ${ran.exitCode}`))
776}
777
778// 보고 있는 문서인지. 열 때 실제 경로로 바꿔 뒀으니 다른 모양의 경로도 실제 경로로 견준다.
779async function isPreviewed($: EngineInterface, path: string) {
780  const shown = await read($, previewFile)
781  if (shown === null) return false
782  if (shown.path === path) return true
783  const real = await $.fs.stat(path, { resolve: true }).then(
784    stat => stat.realPath,
785    () => undefined,
786  )
787  return real === shown.path
788}
789
790// 행 끝의 ◫ 칩: 쉴 때는 흐리고 마우스 아래에서 진해진다.
791function previewChip(els: Els, $: EngineInterface, key: string, path: string, label = T.previewChip) {
792  return <els.Button key={`preview-${key}`} plain dimColor label={label} onPress={() => void openPreview($, path).catch(() => undefined)} />
793}
794
795async function openDiffAt($: EngineInterface, path: string) {
796  await refreshDiffView($, 'uncommitted')
797  const inGit = matchDiffFile(await read($, diff), path)
798  // git 이 모르는 파일(저장소 밖)은 세션 편집 기록에서 찾는다. 경로는 도구가 준 절대 경로다.
799  const outside = inGit === null ? matchDiffFile(outsideEdits(sessionEditsOf(await read($, runs)), await read($, repo)), path) : null
800  const target = inGit ?? (outside === null ? null : `${OUTSIDE}${outside}`)
801  await $.ui.open({ id: PANE, title: T.paneChanges, focus: true })
802  if (target === null) {
803    $.ui.toast(T.notInDiff)
804    return
805  }
806  // git 밖 파일이면 묶음도 편다: 접힌 묶음 안의 파일 머리 띠는 그리지 않아 스크롤해 갈 곳이 없다.
807  await update($, open, state => ({ ...onlyOpen(state, target), ...(inGit === null ? { [OUTSIDE_GROUP]: false } : {}) }))
808  await scrollToFile($, target)
809}
810
811// 창 맨 위 행이 속한 파일: 머리 띠가 그 행이거나 그 위에 있는 마지막 파일. 첫 머리 띠보다 위면 -1.
812export function headAt(heads: ReadonlyArray<{ top: number }>, offset: number): number {
813  let at = -1
814  heads.forEach((head, index) => {
815    if (head.top <= offset) at = index
816  })
817  return at
818}
819
820// n·p 가 기준으로 삼는 지금 파일: 하나만 펴져 있으면 그것, 아니면 마지막으로 스크롤해 간 파일, 그것도 없으면 창 맨 위 행의 파일.
821// 창 위치만 보면 안 된다: 뒤쪽 파일은 내용이 짧아 엔진이 창을 끝에서 깎아, 머리 띠가 맨 위에 오지 못하고 창 맨 위는 앞 파일이 된다.
822export function currentHead(heads: ReadonlyArray<{ id: string; top: number }>, folds: Record<string, boolean>, cursor: string | null, offset: number): number {
823  const opened = heads.flatMap((head, index) => (folds[`fold:${head.id}`] === false ? [index] : []))
824  if (opened.length === 1) return opened[0]!
825  const at = cursor === null ? -1 : heads.findIndex(head => head.id === cursor)
826  return at !== -1 ? at : headAt(heads, offset)
827}
828
829// n·p: 다음·이전 파일. 하나만 펴 보는 중이면(펴진 파일이 하나 이하) 그 파일을 펴고(앞 파일은 접힌다), 여럿 펴 두었으면 머리 띠로 간다.
830async function stepFile($: EngineInterface, by: 1 | -1) {
831  const heads = diffHeads
832  const state = await read($, open)
833  const at = currentHead(heads, state, diffCursor, paneOffsets.get(PANE) ?? 0)
834  const target = at === -1 ? (by > 0 ? heads[0] : undefined) : heads[at + by]
835  if (!target) return
836  const opened = heads.filter(head => state[`fold:${head.id}`] === false).length
837  if ((state[`fold:${target.id}`] ?? true) && opened <= 1) await pickFile($, target.id)
838  else await scrollToFile($, target.id)
839}
840
841// diff 패널 파일은 하나만 펴진다: 펴 둔 파일 키를 모두 접고 이것만 편다. 기록이 없는 파일은 접힌 것이다.
842function onlyOpen(state: Record<string, boolean>, id: string): Record<string, boolean> {
843  const others = Object.keys(state).filter(key => key.startsWith('fold:') && !state[key])
844  return { ...state, ...Object.fromEntries(others.map(key => [key, true])), [`fold:${id}`]: false }
845}
846
847// 파일 머리 띠를 누름: 접혀 있으면 그것만 펴고 그 머리 띠로 스크롤한다(위에 펴져 있던 파일이 접혀 자리가 당겨진다). 펴져 있으면 접는다.
848async function pickFile($: EngineInterface, id: string) {
849  const isOpening = (await read($, open))[`fold:${id}`] ?? true
850  await update($, open, state => (isOpening ? onlyOpen(state, id) : { ...state, [`fold:${id}`]: true }))
851  if (isOpening) await scrollToFile($, id)
852}
853
854// 상태를 바꾼 직후 스크롤하면 엔진은 아직 앞 그림(위 파일이 펴진 자리)으로 머리 띠를 찾아 엉뚱한 곳에 선다.
855// 그 파일이 펴진 그림이 그려질 때까지 기다린다. 막 연 패널은 아직 그려지기 전이라 스크롤이 거부되니("not this plugin's site") 잠깐 다시 한다.
856async function scrollToFile($: EngineInterface, id: string) {
857  for (let tries = 0; tries < 20 && diffDrawnFolds[`fold:${id}`] !== false; tries++) await $.clock.sleep(25).catch(() => undefined)
858  for (let tries = 0; tries < 8; tries++) {
859    const moved = await $.ui.scroll({ to: { key: `file-${id}` }, in: PANE, block: 'start' }).catch(() => ({ deny: 'failed' }))
860    if (!moved.deny) {
861      diffCursor = id
862      return
863    }
864    await $.clock.sleep(100).catch(() => undefined)
865  }
866}
867
868// PR 바: 턴이 끝날 때마다 다시 읽되 30초 안에는 건너뛴다(gh·glab 은 네트워크를 탄다). 도구가 없거나 어느
869// 호스트의 저장소도 아니면(isSticky) 같은 브랜치에서는 다시 묻지 않는다. 패널을 열거나 ↻ 를 누르면 바로 읽는다.
870// 체크(GitLab 은 파이프라인 job)가 도는 동안은 턴 밖에서도 다시 읽고, 다 끝나면 멈춘다. 결과가 오지 않는 체크
871// (GitHub EXPECTED, runner 를 기다리는 job)는 끝나지 않으므로, 체크 상태가 그대로면 간격을 PR_POLL 에서 두 배씩
872// PR_POLL_MAX 까지 늘린다(gh·glab 사용 한도). 무엇이든 바뀌거나 새로 푸시하면 PR_POLL 로 돌아간다.
873const PR_TTL = 30_000
874const PR_POLL = 15_000
875const PR_POLL_MAX = 120_000
876let prFetch: Promise<void> | null = null
877let prPoll: Timer | null = null
878let prDelay = PR_POLL
879let prSeen: string | null = null
880
881const isChecking = (state: PrState | null | undefined) =>
882  state?.status === 'ok' && state.pr?.state === 'OPEN' && state.pr.checks.some(check => check.state === 'pending')
883
884// 다음 주기: 지난번 읽은 것과 head·체크 상태가 같으면 늘리고, 다르면 처음으로.
885function pacePr(state: PrState) {
886  const seen = JSON.stringify([state.pr?.headSha, state.pr?.checks.map(check => [check.name, check.state])])
887  prDelay = seen === prSeen ? Math.min(prDelay * 2, PR_POLL_MAX) : PR_POLL
888  prSeen = seen
889}
890
891function watchPr($: EngineInterface) {
892  if (prPoll !== null) return
893  prPoll = $.clock.after(prDelay, () => {
894    prPoll = null
895    // 다시 읽어 체크가 아직 돌면 refreshPr 이 다음 주기를 건다.
896    void refreshPr($, false).catch(() => undefined)
897  })
898}
899
900async function refreshPr($: EngineInterface, force: boolean) {
901  if (prFetch) return prFetch
902  prFetch = (async () => {
903    const [branchRan, now] = await Promise.all([
904      $.process.run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], { timeoutMs: 5000 }).catch(() => null),
905      $.clock.now(),
906    ])
907    const branch = branchRan?.exitCode === 0 ? branchRan.stdout.trim() : null
908    const last = await read($, pr)
909    if (branch === null || branch === 'HEAD') {
910      await update($, pr, (): PrState => ({ status: 'none', branch, pr: null, at: now }))
911      return
912    }
913    const ttl = isChecking(last) ? PR_POLL / 2 : PR_TTL
914    if (!force && last && last.branch === branch && ((last.status === 'off' && last.isSticky) || now - last.at < ttl)) {
915      // 다시 불러온 모듈은 타이머가 없다: 저장된 상태에 도는 체크가 있으면 다시 건다.
916      if (isChecking(last)) watchPr($)
917      return
918    }
919    if (force || last?.branch !== branch) await update($, pr, (previous): PrState => ({ status: 'loading', branch, pr: previous?.branch === branch ? previous.pr : null, at: now }))
920    const next = await fetchReview($, branch, now)
921    await update($, pr, () => next)
922    // 다음 주기는 방금 읽은 때부터 센다(↻·턴 끝에서 바뀐 것을 보면 길게 걸어 둔 타이머 대신 PR_POLL 로).
923    prPoll?.cancel()
924    prPoll = null
925    if (isChecking(next)) {
926      pacePr(next)
927      watchPr($)
928    } else {
929      prDelay = PR_POLL
930      prSeen = null
931    }
932  })().finally(() => {
933    prFetch = null
934  })
935  return prFetch
936}
937
938async function openDiff($: EngineInterface, scope?: DiffScope) {
939  await refreshDiffView($, scope)
940  await $.ui.open({ id: PANE, title: T.paneChanges, focus: true })
941  // 맨 위에서 보여 준다. 다시 연 패널의 창과 적어 둔 위치(diffWindow)도 이 스크롤로 맞춰진다.
942  await $.ui.scroll({ to: 'start', in: PANE }).catch(() => undefined)
943}
944
945// 열린 패널이 있으면 접고(닫되 제목·스크롤을 적어 둔다), 없으면 접어 둔 패널을 다시 연다.
946// 내용은 store 에 그대로 남아 있어 다시 그리면 같은 화면이다. 엔진에는 패널을 남긴 채 숨기는 API 가 없다.
947// desk-asana·desk-slack 은 folded 의 state.set 을 훅해 자기 패널을 따라 접고 편다(엔진은 다른 플러그인의 패널을
948// 보여 주지도 닫게 하지도 않는다). 그래서 접을 내 패널이 없어도 빈 목록을 써서 알리고, 접은 수는 그쪽 folded 를 더한다.
949async function siblingsFolded($: EngineInterface): Promise<number> {
950  const [asanaPanes, slackPanes] = await Promise.all([read($, asanaFolded), read($, slackFolded)])
951  return (asanaPanes?.length ?? 0) + (slackPanes?.length ?? 0)
952}
953
954// 열린 패널이 하나라도 있으면(desk-asana·desk-slack 것 포함) 접고, 없으면 접어 둔 것을 편다. 이미 접어 둔 것이
955// 있으면 새로 접는 것을 그 목록에 더한다(접은 뒤 다른 패널을 열어 다시 접어도 처음 것이 남는다).
956async function toggleFold($: EngineInterface): Promise<string> {
957  const panes = (await $.ui.panes()).filter(pane => pane.isPlaced)
958  const saved = await read($, folded)
959  const [asanaOpen, slackOpen] = await Promise.all([read($, asanaShown), read($, slackShown)])
960  if (panes.length > 0 || asanaOpen || slackOpen || saved === null) {
961    const fresh = panes.map(pane => ({ id: pane.id, title: pane.title, isShown: pane.isShown, offset: paneOffsets.get(pane.id) ?? 0 }))
962    await update($, folded, () => [...(saved ?? []).filter(pane => !fresh.some(item => item.id === pane.id)), ...fresh])
963    for (const pane of panes) await $.ui.close({ id: pane.id }).catch(() => undefined)
964    // desk-asana·desk-slack 은 패널이 하나씩이라 열려 있던 것이 접힌 수다.
965    const count = panes.length + Number(asanaOpen) + Number(slackOpen)
966    if (count > 0) return T.folded(count)
967    if ((saved ?? []).length === 0 && (await siblingsFolded($)) === 0) await update($, folded, () => null)
968    return T.foldNothing
969  }
970  const count = saved.length + (await siblingsFolded($))
971  await update($, folded, () => null)
972  if (count === 0) return T.foldNothing
973  // 앞에 있던 패널을 마지막에 열어 앞에 오게 한다.
974  const order = [...saved.filter(pane => !pane.isShown), ...saved.filter(pane => pane.isShown)]
975  for (const pane of order) {
976    await $.ui.open({ id: pane.id, title: pane.title, ...(pane.isShown ? { focus: true as const } : {}) })
977    if (pane.offset > 0) await restoreScroll($, pane.id, pane.offset)
978  }
979  return T.unfolded(count)
980}
981
982// 막 연 패널은 아직 그려지기 전이라 스크롤이 거부되거나("not this plugin's site") 빈 내용에 맞춰 0 으로 깎인다.
983// 적어 둔 위치는 ui.scroll 훅이 내용이 그려진 뒤에 offset 으로 바꿔 넣고 지운다. 지워질 때까지 잠깐 다시 한다.
984// 창이 이미 가 있는 끝으로는 움직이지 않아 훅이 불리지 않으므로 양 끝을 차례로 청한다.
985// 명령 안에서 기다린다: 명령이 끝난 뒤 백그라운드에서 돌리면 clock.sleep 이 기다려 주지 않아 그리기 전에 시도가 다 끝났다.
986async function restoreScroll($: EngineInterface, id: string, offset: number) {
987  restoreOffsets.set(id, offset)
988  try {
989    for (let tries = 0; tries < 8 && restoreOffsets.has(id); tries++) {
990      for (const to of ['end', 'start'] as const) {
991        if (!restoreOffsets.has(id)) break
992        await $.ui.scroll({ to, in: id }).catch(() => undefined)
993      }
994      if (restoreOffsets.has(id)) await $.clock.sleep(100).catch(() => undefined)
995    }
996  } finally {
997    restoreOffsets.delete(id)
998  }
999}
1000
1001async function openPr($: EngineInterface) {
1002  const shown = refreshPr($, true).catch(() => undefined)
1003  await $.ui.open({ id: PR_PANE, title: 'PR', focus: true })
1004  await shown
1005}
1006
1007// PR 패널의 머지: Revert 처럼 5초 안에 두 번 눌러야 한다. 누른 순간 패널이 보여 준 PR(head 커밋)로 머지하고
1008// 결과를 알린 뒤 다시 읽는다. 도는 체크가 있으면 통과하면 머지되게 건다.
1009const MERGE_ARM_MS = 5000
1010let merging = false
1011
1012async function mergeFromPane($: EngineInterface, info: PrInfo, action: MergeAction, isArmed: boolean) {
1013  const key = `merge:${info.url}`
1014  if (!isArmed) {
1015    await update($, open, state => ({ ...state, [key]: true }))
1016    $.clock.after(MERGE_ARM_MS, () => void update($, open, state => ({ ...state, [key]: false })))
1017    return
1018  }
1019  await update($, open, state => ({ ...state, [key]: false }))
1020  if (merging) return
1021  merging = true
1022  try {
1023    $.ui.toast(T.merging(prRef(info)))
1024    const result = await mergePr($, info, action)
1025    if (!result.ok) $.ui.toast(T.mergeFailed(result.error))
1026    else $.ui.toast([result.merged ? T.merged(prRef(info)) : T.autoMergeSet(prRef(info)), result.note].filter(Boolean).join(' · '))
1027  } finally {
1028    merging = false
1029  }
1030  await refreshPr($, true).catch(() => undefined)
1031}
1032
1033// 줄 댓글의 diff 범위: 모델이 줄 번호가 어느 판의 것인지 알게.
1034function commentScope(prefix: string, base: string | undefined): string {
1035  if (prefix === OUTSIDE) return 'an edit made this session, outside git'
1036  if (prefix === 'b:') return base ? `branch changes since ${base}` : 'branch changes'
1037  const commit = /^c:([^:]+):$/.exec(prefix)
1038  return commit ? `commit ${commit[1]}` : 'uncommitted changes'
1039}
1040
1041// 줄 번호 누름: 범위를 정하고 입력칸으로 포커스를 옮긴다(다음 그림에 생기는 입력칸을 엔진이 기다려 준다).
1042// 패널 버튼을 클릭해도 패널이 키를 갖지 않아 focus 가 거절되므로, 패널을 focus 로 다시 열어 키를 가져온다.
1043async function pickLine($: EngineInterface, at: LinePress) {
1044  const before = await read($, commentDraft)
1045  const next = pressLine(before, at)
1046  if (!next || before?.patch !== next.patch) draftText = ''
1047  await update($, commentDraft, () => next)
1048  if (!next) return
1049  await $.ui.open({ id: PANE, title: T.paneChanges, focus: true })
1050  await $.ui.focus({ requestId: PANE, key: draftInputKey(next) }).catch(() => undefined)
1051}
1052
1053// 지우기: 범위는 두고 쓴 글만 비운 칸을 새로 그려 그리로 돌아간다.
1054async function clearComment($: EngineInterface) {
1055  draftText = ''
1056  draftRound++
1057  const draft = await read($, commentDraft)
1058  await update($, commentDraft, current => (current ? { ...current } : current))
1059  if (!draft) return
1060  await $.ui.open({ id: PANE, title: T.paneChanges, focus: true })
1061  await $.ui.focus({ requestId: PANE, key: draftInputKey(draft) }).catch(() => undefined)
1062}
1063
1064async function cancelComment($: EngineInterface) {
1065  draftText = ''
1066  await update($, commentDraft, () => null)
1067}
1068
1069// Enter: 글이 있으면 그 범위 줄들과 함께 쌓고, 비었으면 닫는다.
1070async function saveComment($: EngineInterface, draft: CommentDraft, lines: DiffLine[], value: string) {
1071  const body = value.trim()
1072  await cancelComment($)
1073  if (body === '' || lines.length === 0) return
1074  const end = lines[lines.length - 1] as DiffLine
1075  const id = String(++commentSeq)
1076  await update($, lineComments, list => [...list, { id, patch: draft.patch, path: draft.path, scope: draft.scope, end: lineRef(end), lines, body }])
1077}
1078
1079// "Claude에게 맡기기": 입력창이 비어 있으면 채우고, 쓰던 글이 있으면 뒤에 붙인다.
1080async function fillPrompt($: EngineInterface, text: string, done = T.filled) {
1081  const box = await $.prompt.read().catch(() => ({ text: '', cursor: 0 }))
1082  const isEmpty = box.text.trim() === ''
1083  const filled = await $.prompt.fill({ text: isEmpty ? text : `\n\n${text}`, mode: isEmpty ? 'replace' : 'append' }).catch(() => null)
1084  $.ui.toast(filled?.isFilled ? done : T.fillFailed)
1085}
1086
1087// 대화 기록에서 고른 글을 인용으로(턴 끝 줄의 ❝ 칩, /desk-quote). 엔진은 고를 때 알려 주지 않고, 누르거나
1088// 명령을 쳐도 마지막 선택은 남아 있어서 그때 읽는다. 아래 빈 줄은 물어볼 말을 쓸 자리.
1089export function quoteText(text: string): string {
1090  const lines = text.replace(/\s+$/, '').split('\n').map(line => line.trimEnd())
1091  return `${lines.map(line => (line === '' ? '>' : `> ${line}`)).join('\n')}\n\n`
1092}
1093
1094// 쓰던 글이 있으면 인용을 그 위에(앞서 넣은 인용들 다음에) 넣고, 커서는 쓰던 자리에 그대로 둔다.
1095// 질문은 인용 아래에 오고, 치던 손이 끊기지 않는다. 커서가 앞 인용 안에 있었으면 글 첫머리로.
1096export function quoteInto(draft: string, cursor: number, quote: string): { text: string; cursor: number } {
1097  if (draft.trim() === '') return { text: quote, cursor: quote.length }
1098  const lead = /^(?:>[^\n]*(?:\n|$)|\n)*/.exec(draft)?.[0] ?? ''
1099  const head = lead.includes('>') ? lead.replace(/\n*$/, '\n\n') : ''
1100  const rest = draft.slice(lead.length)
1101  const start = head.length + quote.length
1102  return { text: head + quote + rest, cursor: start + Math.max(0, cursor - lead.length) }
1103}
1104
1105async function quoteSelection($: EngineInterface) {
1106  const selected = await $.ui.selection().catch(() => undefined)
1107  if (!selected || selected.text.trim() === '') {
1108    $.ui.toast(T.quoteNone)
1109    return
1110  }
1111  const box = await $.prompt.read().catch(() => ({ text: '', cursor: 0 }))
1112  const next = quoteInto(box.text, box.cursor, quoteText(selected.text))
1113  const filled = await $.prompt.fill({ text: next.text, mode: 'replace', cursor: next.cursor }).catch(() => null)
1114  $.ui.toast(filled?.isFilled ? T.quoted : T.fillFailed)
1115}
1116
1117// diff 패널의 브랜치·커밋 범위. 커밋 안 한 변경은 refreshDiff 의 diff 를 그대로 쓴다.
1118async function findBase($: EngineInterface) {
1119  const opts = { timeoutMs: 8000 }
1120  const [originHead, state, view] = await Promise.all([$.process.run(['git', 'symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD'], opts), read($, pr), read($, diffView)])
1121  // 사람이 고른 기준이 먼저, 그 브랜치가 없어졌으면 자동 후보로.
1122  const auto = baseCandidates(state?.pr?.base ?? null, originHead.exitCode === 0 ? originHead.stdout.trim() : null)
1123  const candidates = view.baseRef ? [view.baseRef, ...auto.filter(ref => ref !== view.baseRef)] : auto
1124  for (const ref of candidates) {
1125    const found = await $.process.run(['git', 'rev-parse', '--verify', '--quiet', `${ref}^{commit}`], opts)
1126    if (found.exitCode !== 0) continue
1127    const base = await $.process.run(['git', 'merge-base', 'HEAD', ref], opts)
1128    if (base.exitCode === 0 && base.stdout.trim() !== '') return { ref, sha: base.stdout.trim() }
1129  }
1130  return null
1131}
1132
1133// 기준 고르기: 목록이 열려 있으면 닫고, 아니면 최근 커밋 순 브랜치(로컬·원격)를 읽어 연다. 지금 기준이 목록에 없으면 맨 앞에.
1134async function toggleBases($: EngineInterface) {
1135  const view = await read($, diffView)
1136  if (view.bases) {
1137    await update($, diffView, previous => ({ ...previous, bases: null }))
1138    return
1139  }
1140  const opts = { timeoutMs: 5000 }
1141  const [refs, branch] = await Promise.all([
1142    $.process.run(['git', 'for-each-ref', '--sort=-committerdate', '--count=40', '--format=%(refname)', 'refs/heads', 'refs/remotes'], opts).catch(() => null),
1143    $.process.run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], opts).catch(() => null),
1144  ])
1145  const found = refs?.exitCode === 0 ? branchChoices(refs.stdout, branch?.exitCode === 0 ? branch.stdout.trim() : null) : []
1146  const now = view.base?.ref
1147  const bases = now && !found.includes(now) ? [now, ...found].slice(0, 8) : found
1148  await update($, diffView, previous => ({ ...previous, bases }))
1149}
1150
1151// 기준을 고르면(null 은 자동) 목록을 닫고 브랜치 전체·커밋별을 그 기준으로 다시 읽는다.
1152async function pickBase($: EngineInterface, ref: string | null) {
1153  await update($, diffView, previous => ({ ...previous, baseRef: ref, bases: null }))
1154  await refreshDiffView($)
1155}
1156
1157// 안 바뀐 구간을 누름: 새 쪽 파일(작업 트리, 커밋별이면 그 커밋)에서 구간의 줄을 읽어 그 자리에 편다.
1158// 읽은 줄 수가 구간과 다르면 파일이 diff 를 읽은 뒤 바뀐 것이라 diff 를 다시 읽는다.
1159type GapSource = { kind: 'worktree' } | { kind: 'commit'; sha: string }
1160type GapPress = { key: string; patch: string; path: string; source: GapSource; gap: Gap }
1161
1162async function openGap($: EngineInterface, at: GapPress) {
1163  const lines = await gapSource($, at.path, at.source)
1164  if (lines === null) {
1165    $.ui.toast(T.gapUnreadable)
1166    return
1167  }
1168  const hidden = lines.slice(at.gap.newStart - 1, at.gap.newStart - 1 + at.gap.count)
1169  if (hidden.length !== at.gap.count) {
1170    await refreshDiffView($)
1171    return
1172  }
1173  await update($, diffGaps, gaps => {
1174    const kept = gaps[at.key]?.patch === at.patch ? (gaps[at.key]?.lines ?? {}) : {}
1175    return { ...gaps, [at.key]: { patch: at.patch, lines: { ...kept, [at.gap.newStart]: hidden.map(untab) } } }
1176  })
1177}
1178
1179// 새 쪽 파일의 줄들. 커밋 안의 파일은 git cat-file 로(커밋:경로는 stdin 으로), 첫 줄은 머리말이고 끝에 줄바꿈 하나가 붙는다.
1180async function gapSource($: EngineInterface, path: string, source: GapSource): Promise<string[] | null> {
1181  if (source.kind === 'worktree') {
1182    const root = (await read($, repo))?.root
1183    const text = root ? await $.fs.read(`${root}/${path}`).catch(() => null) : null
1184    return text === null ? null : text.split('\n')
1185  }
1186  const ran = await $.process.run(['git', 'cat-file', '--batch'], { timeoutMs: 5000, stdin: `${source.sha}:${path}\n` }).catch(() => null)
1187  const end = ran?.exitCode === 0 ? ran.stdout.indexOf('\n') : -1
1188  if (!ran || end < 0 || !ran.stdout.slice(0, end).includes(' blob ')) return null
1189  return ran.stdout.slice(end + 1).replace(/\n$/, '').split('\n')
1190}
1191
1192// 거르기 줄: 열면 입력칸에 키를 준다(막 그려지는 중이면 잠깐 다시). 닫으면 거른 글도 지운다.
1193async function toggleFilter($: EngineInterface) {
1194  const filter = await read($, diffFilter)
1195  if (filter.isOpen) {
1196    await update($, diffFilter, () => ({ isOpen: false, query: '' }))
1197    return
1198  }
1199  await update($, diffFilter, previous => ({ ...previous, isOpen: true }))
1200  await $.ui.open({ id: PANE, title: T.paneChanges, focus: true })
hooks/images.ts 113 lines
1import type { Graphics, ImageInfo } from '../types'
2
3// 붙여 넣은 이미지는 세션 임시 폴더(/tmp/claude-<uid>/<프로젝트>/<세션>/images)의 N.png 에 [Image #N] 번호 그대로 저장된다.
4// 파일 이름의 번호. N.png 가 아니면 null.
5export function imageNumber(name: string): string | null {
6  return /^(\d+)\.png$/.exec(name)?.[1] ?? null
7}
8
9// PNG 앞 24바이트(IHDR)의 가로·세로. 짧거나 0 이면 null.
10export function pngSize(bytes: ArrayLike<number>): { width: number; height: number } | null {
11  if (bytes.length < 24) return null
12  const word = (at: number) => Array.from({ length: 4 }, (_, i) => bytes[at + i] ?? 0).reduce((value, byte) => value * 256 + byte, 0)
13  const width = word(16)
14  const height = word(20)
15  return width > 0 && height > 0 ? { width, height } : null
16}
17
18// 썸네일 칸 수. 터미널 셀은 세로가 가로의 약 두 배라 행 수는 절반으로 센다.
19export function thumbnailSize(image: ImageInfo, maxColumns: number, maxRows = 12) {
20  let columns = Math.max(4, maxColumns)
21  let rows = Math.round((columns * image.height) / image.width / 2)
22  if (rows > maxRows) {
23    rows = maxRows
24    columns = Math.max(4, Math.round((rows * 2 * image.width) / image.height))
25  }
26  return { columns: Math.min(columns, 255), rows: Math.max(1, Math.min(rows, 255)) }
27}
28
29export const IMAGE_TOKEN = /\[Image #(\d+)\]/g
30
31// herdr 는 설정(~/.config/herdr/config.toml)의 [experimental] kitty_graphics = true 일 때만 kitty 그래픽을 바깥 터미널로 넘긴다.
32export function herdrGraphicsOn(config: string): boolean {
33  return /^[ \t]*kitty_graphics[ \t]*=[ \t]*true/m.test(config)
34}
35
36// tmux 에 이 창의 바깥 터미널과 그림 통과 설정을 묻는 형식. 엔진도 같은 것을 물어 tmux 안에서 그릴지 정한다.
37export const TMUX_GRAPHICS_FORMAT = ['#{client_termtype}', '#{allow-passthrough}', '#{focus-events}', '#{window_bigger}'].join('\t')
38
39// '0.35.1' 이 [0, 28] 이상인지. 숫자가 아니면 false.
40function versionAtLeast(text: string, least: number[]): boolean {
41  const parts = /^\s*(\d+)(?:\.(\d+))?(?:\.(\d+))?/.exec(text)
42  if (!parts) return false
43  const have = [1, 2, 3].map(i => Number(parts[i] ?? 0))
44  for (let i = 0; i < 3; i++) if (have[i] !== (least[i] ?? 0)) return (have[i] ?? 0) > (least[i] ?? 0)
45  return true
46}
47
48// tmux 안에서 엔진이 그림을 그리는지(2.1.310): tmux 3.3 이상에서 allow-passthrough 와 focus-events 가 켜져 있고
49// 바깥 터미널(client_termtype)이 kitty 0.28 이상·Ghostty 면 kitty 그래픽을, iTerm2 3.5 이상이면 iTerm2 그림을 그린다.
50// iTerm2 는 allow-passthrough 가 all 이 아니라 on 이어야 하고 창이 터미널보다 크지 않아야 한다.
51// 바이트만 넘어가므로 kitty 도 파일 이름 대신 바이트를 준다('kitty-bytes'). reply 는 TMUX_GRAPHICS_FORMAT 의 대답.
52export function tmuxGraphicsOf(reply: string): Graphics {
53  const [termtype = '', passthrough = '', focusEvents = '', bigger = ''] = reply.replace(/\r?\n$/, '').split('\t')
54  if (!['on', '1', 'all'].includes(passthrough) || focusEvents !== '1') return null
55  if (termtype.startsWith('kitty(')) return versionAtLeast(termtype.slice(6), [0, 28]) ? 'kitty-bytes' : null
56  if (['kitty', 'ghostty'].some(name => termtype === name || termtype.startsWith(`${name} `))) return 'kitty-bytes'
57  if (/^iTerm2\s/.test(termtype) && versionAtLeast(termtype.slice(6), [3, 5])) return passthrough === 'on' && bigger !== '1' ? 'iterm' : null
58  return null
59}
60
61// 그림을 그릴 수 있는 환경인지. tmux 는 tmuxReply(tmuxGraphicsOf) 로 정하고, 못 물었으면 그리지 않는다.
62// zellij 는 통과시키지 않아 그림 대신 alt 글자가 나오므로 그리지 않는다.
63// herdr 는 kitty_graphics 를 켰을 때만(herdrGraphics) 넘기는데, 엔진은 터미널 이름을 물어 kitty·ghostty 일 때만
64// 그림을 그리고 herdr 안에서는 herdr 가 대답하므로 CLAUDE_CODE_FORCE_TERMINAL_IMAGES 까지 켜야 그린다.
65// iTerm2 는 엔진이 XTVERSION 대답의 버전을 보는데, iTerm2 가 TERM_PROGRAM_VERSION 에 같은 버전을 적는다.
66// CLAUDE_CODE_ALT_SCREEN_FULL_REPAINT 면 엔진이 매 화면 그림을 다시 보내야 해서 iTerm2 는 그리지 않는다.
67export function graphicsOf(env: Record<string, string | undefined>, herdrGraphics = false, tmuxReply: string | null = null): Graphics {
68  if (env.TMUX) {
69    const kind = tmuxReply === null ? null : tmuxGraphicsOf(tmuxReply)
70    return kind === 'iterm' && env.CLAUDE_CODE_ALT_SCREEN_FULL_REPAINT ? null : kind
71  }
72  if (env.ZELLIJ) return null
73  if (env.HERDR_ENV === '1') {
74    return herdrGraphics && ['1', 'true'].includes((env.CLAUDE_CODE_FORCE_TERMINAL_IMAGES ?? '').toLowerCase()) ? 'kitty' : null
75  }
76  const term = (env.TERM ?? '').toLowerCase()
77  const program = (env.TERM_PROGRAM ?? '').toLowerCase()
78  if (term.includes('kitty') || term.includes('ghostty') || ['ghostty', 'kitty', 'wezterm'].includes(program)) return 'kitty'
79  if (program !== 'iterm.app' || env.CLAUDE_CODE_ALT_SCREEN_FULL_REPAINT) return null
80  const [major = 0, minor = 0] = (env.TERM_PROGRAM_VERSION ?? '').split('.').map(Number)
81  return major > 3 || (major === 3 && minor >= 5) ? 'iterm' : null
82}
83
84export type Corner = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'
85
86// 여러 줄 말풍선의 모서리 한 칸 그림(RGBA). 칸 너비를 반지름으로 바깥 모서리를 둥글게 비우고 나머지는
87// 말풍선 색으로 채운다. 가장자리는 한 픽셀을 4x4 로 나눠 덮인 비율을 알파로 써서 부드럽게 한다.
88// 터미널은 그림을 늘이지 않고 비율을 지켜 칸에 맞춘 뒤 픽셀로 반올림한다(Ghostty). 그림 비율이 칸과 다르면
89// 모서리 칸 위아래가 비어 줄 사이에 틈이 난다 — 16x32 는 11x24 칸에서 1px, 14x32 칸에서 2px.
90// 27x61 은 두 칸 모두 반올림으로 꽉 차고, 경계(x.5)까지 0.12px 여유가 있다.
91export const CORNER_SIZE = { width: 27, height: 61 } as const
92
93export function cornerPixels(corner: Corner, color: string): Uint8Array {
94  const { width, height } = CORNER_SIZE
95  const value = parseInt(/^#?([0-9a-f]{6})$/i.exec(color.trim())?.[1] ?? '000000', 16)
96  const radius = width
97  const centerX = corner.endsWith('left') ? width : 0
98  const top = corner.startsWith('top')
99  const centerY = top ? radius : height - radius
100  const inside = (x: number, y: number) =>
101    (top ? y >= centerY : y <= centerY) || (x - centerX) ** 2 + (y - centerY) ** 2 <= radius * radius
102  const pixels = new Uint8Array(width * height * 4)
103  for (let y = 0; y < height; y++) {
104    for (let x = 0; x < width; x++) {
105      let hit = 0
106      for (let i = 0; i < 4; i++) for (let j = 0; j < 4; j++) if (inside(x + (i + 0.5) / 4, y + (j + 0.5) / 4)) hit++
107      const at = (y * width + x) * 4
108      pixels.set([(value >> 16) & 255, (value >> 8) & 255, value & 255, Math.round((255 * hit) / 16)], at)
109    }
110  }
111  return pixels
112}
113
hooks/markdown.tsx 554 lines
1import type { Elements, UiPressArgument } from 'claude-code'
2
3import { renderDiagram } from './diagram'
4
5// 데스크톱 앱 산문 스타일로 마크다운을 Box/Text 트리로 그린다.
6// 엔진의 Markdown 요소는 표·인용·코드 블록 모양을 바꿀 수 없어서 직접 파싱한다.
7
8export type Palette = {
9  text: string
10  muted: string
11  border: string
12  code: string
13  link: string
14  // 인라인 코드 바탕. 터미널 배경을 알 때만 칠한다.
15  codeBg?: string
16  // 다이어그램 화살표 강조색.
17  accent: string
18}
19
20export type Inline =
21  | { kind: 'text'; text: string }
22  | { kind: 'code'; text: string }
23  | { kind: 'bold' | 'italic' | 'strike'; children: Inline[] }
24  | { kind: 'link'; href: string; children: Inline[] }
25
26type Align = 'left' | 'center' | 'right'
27
28export type Block =
29  | { kind: 'heading'; level: number; text: string }
30  | { kind: 'paragraph'; text: string }
31  | { kind: 'code'; language?: string; source: string }
32  | { kind: 'table'; header: string[]; align: Align[]; rows: string[][] }
33  | { kind: 'list'; items: { level: number; marker: string; text: string }[] }
34  | { kind: 'quote'; blocks: Block[]; raw: string }
35  | { kind: 'rule' }
36
37// 한글·CJK·이모지는 터미널에서 두 칸이다.
38export function cellWidth(text: string): number {
39  let width = 0
40  for (const ch of text) {
41    const code = ch.codePointAt(0) ?? 0
42    const isWide =
43      (code >= 0x1100 && code <= 0x115f) ||
44      (code >= 0x2e80 && code <= 0xa4cf) ||
45      (code >= 0xac00 && code <= 0xd7a3) ||
46      (code >= 0xf900 && code <= 0xfaff) ||
47      (code >= 0xfe30 && code <= 0xfe4f) ||
48      (code >= 0xff00 && code <= 0xff60) ||
49      (code >= 0xffe0 && code <= 0xffe6) ||
50      (code >= 0x1f300 && code <= 0x1faff)
51    width += isWide ? 2 : 1
52  }
53  return width
54}
55
56// 여는 펜스 뒤 info string 은 첫 단어만 언어로 쓰고 나머지(title="…" 등)는 버린다.
57const FENCE = /^\s*(`{3,}|~{3,})\s*([^\s`]*)[^`]*$/
58const HEADING = /^(#{1,6})\s+(.*?)\s*#*\s*$/
59const RULE = /^\s*([-*_])(\s*\1){2,}\s*$/
60const BULLETS = ['•', '◦', '▪']
61const LIST_ITEM = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/
62const TABLE_SEPARATOR = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/
63
64function splitRow(line: string): string[] {
65  const trimmed = line.trim().replace(/^\|/, '').replace(/\|$/, '')
66  const cells: string[] = []
67  let current = ''
68  let inCode = false
69  for (let i = 0; i < trimmed.length; i++) {
70    const ch = trimmed[i]
71    if (ch === '\\' && trimmed[i + 1] === '|') {
72      current += '|'
73      i++
74    } else if (ch === '`') {
75      inCode = !inCode
76      current += ch
77    } else if (ch === '|' && !inCode) {
78      cells.push(current.trim())
79      current = ''
80    } else {
81      current += ch
82    }
83  }
84  cells.push(current.trim())
85  return cells
86}
87
88function isBlockStart(line: string, next: string | undefined): boolean {
89  return (
90    FENCE.test(line) ||
91    HEADING.test(line) ||
92    RULE.test(line) ||
93    LIST_ITEM.test(line) ||
94    /^\s*>/.test(line) ||
95    (line.includes('|') && next !== undefined && TABLE_SEPARATOR.test(next) && next.includes('-'))
96  )
97}
98
99export function parseBlocks(markdown: string): Block[] {
100  const lines = markdown.replace(/\r\n?/g, '\n').split('\n')
101  const blocks: Block[] = []
102  let i = 0
103
104  while (i < lines.length) {
105    const line = lines[i] ?? ''
106    const next = lines[i + 1]
107
108    if (line.trim() === '') {
109      i++
110      continue
111    }
112
113    const fence = FENCE.exec(line)
114    if (fence) {
115      const marker = fence[1] ?? '```'
116      const body: string[] = []
117      i++
118      const closes = (candidate: string) => {
119        const trimmed = candidate.trim()
120        return trimmed.length >= marker.length && /^(`+|~+)$/.test(trimmed) && trimmed[0] === marker[0]
121      }
122      while (i < lines.length && !closes(lines[i] ?? '')) {
123        body.push(lines[i] ?? '')
124        i++
125      }
126      i++
127      blocks.push({ kind: 'code', language: fence[2] || undefined, source: body.join('\n') })
128      continue
129    }
130
131    const heading = HEADING.exec(line)
132    if (heading) {
133      blocks.push({ kind: 'heading', level: (heading[1] ?? '#').length, text: heading[2] ?? '' })
134      i++
135      continue
136    }
137
138    if (RULE.test(line) && !LIST_ITEM.test(line.replace(/\s+/g, ''))) {
139      blocks.push({ kind: 'rule' })
140      i++
141      continue
142    }
143
144    if (line.includes('|') && next !== undefined && TABLE_SEPARATOR.test(next) && next.includes('-')) {
145      const header = splitRow(line)
146      const align = splitRow(next).map((cell): Align => {
147        const left = cell.startsWith(':')
148        const right = cell.endsWith(':')
149        return left && right ? 'center' : right ? 'right' : 'left'
150      })
151      const rows: string[][] = []
152      i += 2
153      while (i < lines.length && (lines[i] ?? '').includes('|') && (lines[i] ?? '').trim() !== '') {
154        rows.push(splitRow(lines[i] ?? ''))
155        i++
156      }
157      blocks.push({ kind: 'table', header, align, rows })
158      continue
159    }
160
161    if (/^\s*>/.test(line)) {
162      const body: string[] = []
163      while (i < lines.length && /^\s*>/.test(lines[i] ?? '')) {
164        body.push((lines[i] ?? '').replace(/^\s*>\s?/, ''))
165        i++
166      }
167      blocks.push({ kind: 'quote', blocks: parseBlocks(body.join('\n')), raw: body.join('\n') })
168      continue
169    }
170
171    if (LIST_ITEM.test(line)) {
172      const items: { level: number; marker: string; text: string }[] = []
173      while (i < lines.length) {
174        const current = lines[i] ?? ''
175        const item = LIST_ITEM.exec(current)
176        if (item) {
177          const indent = (item[1] ?? '').replace(/\t/g, '    ').length
178          const marker = item[2] ?? '-'
179          items.push({
180            level: Math.min(4, Math.floor(indent / 2)),
181            marker: /\d/.test(marker) ? marker : (BULLETS[Math.min(4, Math.floor(indent / 2)) % BULLETS.length] ?? '•'),
182            text: item[3] ?? '',
183          })
184          i++
185        } else if (current.trim() !== '' && /^\s+/.test(current) && items.length > 0) {
186          // 들여쓴 이어지는 줄은 앞 항목에 붙인다.
187          const last = items[items.length - 1]
188          if (last) last.text += ' ' + current.trim()
189          i++
190        } else {
191          break
192        }
193      }
194      blocks.push({ kind: 'list', items })
195      continue
196    }
197
198    const paragraph: string[] = []
199    while (i < lines.length) {
200      const current = lines[i] ?? ''
201      if (current.trim() === '' || (paragraph.length > 0 && isBlockStart(current, lines[i + 1]))) break
202      paragraph.push(current.trim())
203      i++
204    }
205    blocks.push({ kind: 'paragraph', text: paragraph.join(' ') })
206  }
207
208  return blocks
209}
210
211// \ 뒤 문장부호는 글자 그대로(CommonMark). 링크 글자에도 \] 가 들어갈 수 있다.
212const INLINE = /\\([!-/:-@[-`{-~])|`([^`]+)`|\*\*(.+?)\*\*|__(.+?)__|~~(.+?)~~|\*([^*\s][^*]*?)\*|\[((?:\\.|[^\]\\])+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)|<(https?:\/\/[^>\s]+)>|(https?:\/\/[^\s<>()]+[^\s<>().,;:!?'"])/
213
214export function parseInline(text: string): Inline[] {
215  const out: Inline[] = []
216  let rest = text
217  while (rest.length > 0) {
218    const match = INLINE.exec(rest)
219    if (!match) {
220      out.push({ kind: 'text', text: rest })
221      break
222    }
223    if (match.index > 0) {
224      out.push({ kind: 'text', text: rest.slice(0, match.index) })
225    }
226    const [whole, escaped, code, bold1, bold2, strike, italic, linkText, linkHref, angleUrl, bareUrl] = match
227    if (escaped !== undefined) out.push({ kind: 'text', text: escaped })
228    else if (code !== undefined) out.push({ kind: 'code', text: code })
229    else if (bold1 !== undefined || bold2 !== undefined) out.push({ kind: 'bold', children: parseInline(bold1 ?? bold2 ?? '') })
230    else if (strike !== undefined) out.push({ kind: 'strike', children: parseInline(strike) })
231    else if (italic !== undefined) out.push({ kind: 'italic', children: parseInline(italic) })
232    else if (linkText !== undefined && linkHref !== undefined) out.push({ kind: 'link', href: linkHref, children: parseInline(linkText) })
233    else {
234      const url = angleUrl ?? bareUrl ?? whole
235      out.push({ kind: 'link', href: url, children: [{ kind: 'text', text: url }] })
236    }
237    rest = rest.slice(match.index + whole.length)
238  }
239  return out
240}
241
242// 엔진 Link 는 줄이 넘어가면 첫 줄에만 걸린다(2.1.302). 주소가 곧 글자인 링크는 한 줄에 들어가게
243// 가운데를 줄여 그린다: 줄바꿈은 단어 단위라 이 길이면 통째로 다음 줄로 넘어간다.
244const URL_LABEL = 40
245const isUrl = (text: string) => /^https?:\/\/\S+$/.test(text)
246
247export function urlLabel(url: string): string {
248  if (cellWidth(url) <= URL_LABEL) return url
249  const bare = url.replace(/^https?:\/\//, '')
250  return bare.length <= URL_LABEL ? bare : `${bare.slice(0, 24)}…${bare.slice(-15)}`
251}
252
253// 링크의 글자가 주소 그대로면 줄인 문구를 돌려준다.
254function linkLabel(node: Extract<Inline, { kind: 'link' }>): string | null {
255  const [only] = node.children
256  return node.children.length === 1 && only?.kind === 'text' && only.text === node.href && isUrl(node.href) ? urlLabel(node.href) : null
257}
258
259// 그려질 칸 수. 바탕을 칠한 인라인 코드는 앞뒤 공백 한 칸씩이 더 붙는다.
260export function inlineWidth(nodes: Inline[], codePadding: number): number {
261  return nodes.reduce(
262    (sum, node) =>
263      sum +
264      (node.kind === 'text'
265        ? cellWidth(node.text)
266        : node.kind === 'code'
267          ? cellWidth(isUrl(node.text) ? urlLabel(node.text) : node.text) + codePadding * 2
268          : node.kind === 'link' && linkLabel(node) !== null
269            ? cellWidth(linkLabel(node) ?? '')
270            : inlineWidth(node.children, codePadding)),
271    0,
272  )
273}
274
275export function plainText(nodes: Inline[]): string {
276  return nodes
277    .map(node => (node.kind === 'text' || node.kind === 'code' ? node.text : plainText(node.children)))
278    .join('')
279}
280
281// 표 열 너비: 자연 너비가 들어가면 그대로, 넘치면 좁은 열은 지키고 넓은 열부터 줄인다.
282export function columnWidths(natural: number[], room: number, fill = false): number[] {
283  const padding = 2
284  const total = natural.reduce((sum, width) => sum + width + padding, 0)
285  if (total <= room) {
286    if (!fill) return natural
287    const content = natural.reduce((sum, width) => sum + width, 0)
288    const extra = room - total
289    const grown = natural.map(width => width + Math.floor((extra * width) / Math.max(1, content)))
290    const last = grown.length - 1
291    grown[last] = (grown[last] ?? 0) + room - grown.reduce((sum, width) => sum + width + padding, 0)
292    return grown
293  }
294  let budget = Math.max(natural.length * (4 + padding), room) - natural.length * padding
295  const widths = natural.map(() => 0)
296  let open = natural.map((_, index) => index)
297  while (open.length > 0) {
298    const share = Math.floor(budget / open.length)
299    const fits = open.filter(index => (natural[index] ?? 0) <= share)
300    if (fits.length === 0) {
301      open.forEach((index, n) => (widths[index] = Math.max(4, share + (n < budget - share * open.length ? 1 : 0))))
302      break
303    }
304    for (const index of fits) {
305      widths[index] = natural[index] ?? 0
306      budget -= natural[index] ?? 0
307    }
308    open = open.filter(index => !fits.includes(index))
309  }
310  return widths
311}
312
313type Els = Elements['terminal']
314
315export const ALERT = /^\s*\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\][ \t]*\n?/i
316
317export const ALERTS: Record<string, { title: string; color: string }> = {
318  NOTE: { title: 'ⓘ Note', color: 'suggestion' },
319  TIP: { title: '✓ Tip', color: 'success' },
320  IMPORTANT: { title: '! Important', color: 'claude' },
321  WARNING: { title: '⚠ Warning', color: 'warning' },
322  CAUTION: { title: '✕ Caution', color: 'error' },
323}
324
325// 파일 맨 앞의 YAML front matter(--- … ---)를 떼어 낸다. 키: 값 줄만 모으고, 닫는 줄이 없으면 본문 그대로.
326export function splitFrontMatter(markdown: string): { fields: [string, string][]; body: string } {
327  const lines = markdown.replace(/\r\n?/g, '\n').split('\n')
328  if (lines[0]?.trim() !== '---') return { fields: [], body: markdown }
329  const end = lines.findIndex((line, index) => index > 0 && /^(---|\.\.\.)\s*$/.test(line))
330  if (end < 0) return { fields: [], body: markdown }
331  const fields = lines
332    .slice(1, end)
333    .map(line => /^([^\s:#][^:]*):\s*(.*)$/.exec(line))
334    .filter((match): match is RegExpExecArray => match !== null)
335    .map(match => [match[1] ?? '', (match[2] ?? '').replace(/^(["'])(.*)\1$/, '$2')] as [string, string])
336  return { fields, body: lines.slice(end + 1).join('\n') }
337}
338
339// onCopy 가 있으면 코드 블록 위 테두리 오른쪽에 마우스를 올렸을 때만 보이는 "⧉ copy" 버튼을 단다.
340// document 는 파일 한 편을 읽는 패널용: 제목 단계를 색·밑줄로 나누고 front matter 를 흐린 머리로 접는다.
341export type MarkdownOptions = { onCopy?: (source: string, press: UiPressArgument) => void; document?: boolean }
342
343export function renderMarkdown(markdown: string, els: Els, colors: Palette, columns: number, options: MarkdownOptions = {}) {
344  const { Box, Text, Code, Link, Button } = els
345  const codePadding = colors.codeBg ? 1 : 0
346
347  const inline = (nodes: Inline[], key: string): (string | JSX.Element)[] =>
348    nodes.map((node, index) => {
349      const k = `${key}.${index}`
350      switch (node.kind) {
351        case 'text':
352          return node.text
353        case 'code': {
354          // 백틱 안 주소도 누를 수 있게(엔진 Markdown 처럼).
355          const text = isUrl(node.text) ? <Link href={node.text}>{urlLabel(node.text)}</Link> : node.text
356          return colors.codeBg ? (
357            <Text color={colors.code} backgroundColor={colors.codeBg}>
358              {' '}
359              {text}{' '}
360            </Text>
361          ) : (
362            <Text color={colors.code}>{text}</Text>
363          )
364        }
365        case 'bold':
366          return <Text weight="semibold">{inline(node.children, k)}</Text>
367        case 'italic':
368          return <Text italic>{inline(node.children, k)}</Text>
369        case 'strike':
370          return <Text strikethrough>{inline(node.children, k)}</Text>
371        case 'link':
372          return (
373            <Text color={colors.link} underline>
374              <Link href={node.href}>{linkLabel(node) ?? inline(node.children, k)}</Link>
375            </Text>
376          )
377      }
378    })
379
380  const prose = (text: string, key: string, props: Record<string, unknown> = {}) => (
381    <Text color={colors.text} {...props}>
382      {inline(parseInline(text), key)}
383    </Text>
384  )
385
386  const table = (block: Extract<Block, { kind: 'table' }>, key: string, room: number) => {
387    const count = Math.max(block.header.length, ...block.rows.map(row => row.length))
388    const cell = (row: string[], index: number) => row[index] ?? ''
389    const natural = Array.from({ length: count }, (_, index) =>
390      Math.max(
391        1,
392        inlineWidth(parseInline(cell(block.header, index)), codePadding),
393        ...block.rows.map(row => inlineWidth(parseInline(cell(row, index)), codePadding)),
394      ),
395    )
396    // 데스크톱 메시지 열처럼 폭을 채우되, 아주 넓은 터미널에서 늘어지지 않게 100칸에서 멈춘다.
397    const widths = columnWidths(natural, Math.min(room, 100) - 2, true)
398    const inner = widths.reduce((sum, width) => sum + width + 2, 0)
399    const justify = (index: number) =>
400      block.align[index] === 'right' ? 'flex-end' : block.align[index] === 'center' ? 'center' : 'flex-start'
401    const headerFill = colors.codeBg ? { backgroundColor: colors.codeBg } : {}
402    const row = (cells: string[], rowKey: string, isHeader: boolean) => (
403      <Box flexDirection="row" {...(isHeader ? headerFill : {})}>
404        {widths.map((width, index) => (
405          <Box width={width + 2} paddingX={1} justifyContent={justify(index)} {...(isHeader ? headerFill : {})}>
406            {prose(cell(cells, index), `${rowKey}.${index}`, isHeader ? (colors.codeBg ? headerFill : { weight: 'semibold' }) : {})}
407          </Box>
408        ))}
409      </Box>
410    )
411    const rule = <Text color={colors.border}>{'─'.repeat(inner)}</Text>
412
413    return (
414      <Box flexDirection="column" alignSelf="flex-start" borderStyle="round" borderColor={colors.border}>
415        {row(block.header, `${key}.h`, true)}
416        {block.rows.flatMap((cells, index) => [rule, row(cells, `${key}.${index}`, false)])}
417      </Box>
418    )
419  }
420
421  const blocks = (list: Block[], key: string, room: number, tone?: string): JSX.Element[] =>
422    list.map((block, index) => {
423      const k = `${key}.${index}`
424      const gap = index === 0 ? 0 : 1
425      const toned = tone ? { color: tone } : {}
426      switch (block.kind) {
427        case 'heading':
428          // 문서: H1 은 강조색, H1·H2 는 아래에 가로줄. 위는 한 줄 더 띄워 절이 갈리게 한다.
429          if (options.document && !tone) {
430            const underline = block.level <= 2
431            return (
432              <Box marginTop={index === 0 ? 0 : 2} flexDirection="column">
433                {prose(block.text, k, { weight: 'semibold', ...(block.level === 1 ? { color: colors.accent } : {}) })}
434                {underline && <Text color={colors.border}>{'─'.repeat(Math.max(4, Math.min(room, 100)))}</Text>}
435              </Box>
436            )
437          }
438          return <Box marginTop={gap}>{prose(block.text, k, { weight: 'semibold', ...toned })}</Box>
439        case 'paragraph':
440          return <Box marginTop={gap}>{prose(block.text, k, toned)}</Box>
441        case 'rule':
442          return (
443            <Box marginTop={gap}>
444              <Text color={colors.border}>{'─'.repeat(Math.max(4, Math.min(room, 80)))}</Text>
445            </Box>
446          )
447        // mermaid 는 박스 문자 그림으로 그린다(lovely-mermaid). 폭이 모자라거나 못 그리는 문법이면 코드 블록으로.
448        case 'code':
449          if (block.language === 'mermaid') {
450            const diagram = renderDiagram(block.source)
451            if (diagram !== null && diagram.width + 6 <= room) {
452              const tone = { border: colors.muted, line: colors.muted, arrow: colors.accent, label: colors.muted, text: colors.text }
453              return (
454                <Box marginTop={gap} flexDirection="column" alignSelf="flex-start" borderStyle="round" borderColor={colors.border} paddingX={2} paddingY={1}>
455                  {diagram.rows.map(row => (
456                    <Text wrap="truncate-end">
457                      {row.length === 0
458                        ? ' '
459                        : row.map(seg =>
460                            seg.href ? (
461                              <Text color={colors.link} underline>
462                                <Link href={seg.href}>{seg.text}</Link>
463                              </Text>
464                            ) : (
465                              <Text color={tone[seg.kind]} italic={seg.kind === 'label'}>
466                                {seg.text}
467                              </Text>
468                            ),
469                          )}
470                    </Text>
471                  ))}
472                </Box>
473              )
474            }
475          }
476          {
477            const code = (
478              <Box flexDirection="column" borderStyle="round" borderColor={colors.border} paddingX={1}>
479                <Code source={block.source} language={block.language} wrap="wrap" />
480              </Box>
481            )
482            const onCopy = options.onCopy
483            if (!onCopy) return <Box marginTop={gap}>{code}</Box>
484            return (
485              <Box key={`code${k}`} marginTop={gap} flexDirection="column">
486                {code}
487                <Box position="absolute" top={0} right={2} display="none" hover={{ display: 'flex' }}>
488                  <Button key={`copy${k}`} plain dimColor label=" ⧉ copy " onPress={press => onCopy(block.source, press)} />
489                </Box>
490              </Box>
491            )
492          }
493        case 'table':
494          return <Box marginTop={gap}>{table(block, k, room)}</Box>
495        case 'quote':
496          // GitHub 알림(> [!NOTE] 등): 종류 색 테두리 + 제목 줄.
497          {
498            const alert = ALERT.exec(block.raw)
499            const style = alert ? ALERTS[(alert[1] ?? '').toUpperCase()] : undefined
500            if (alert && style) {
501              return (
502                <Box marginTop={gap} flexDirection="column" borderStyle="round" borderColor={style.color} paddingX={1}>
503                  <Text color={style.color} weight="semibold">
504                    {style.title}
505                  </Text>
506                  {blocks(parseBlocks(block.raw.slice(alert[0].length)), k, room - 4)}
507                </Box>
508              )
509            }
510          }
511          return (
512            <Box marginTop={gap} borderStyle="quote" borderColor={colors.border} paddingLeft={1} flexDirection="column">
513              {blocks(block.blocks, k, room - 2, colors.muted)}
514            </Box>
515          )
516        case 'list':
517          return (
518            <Box marginTop={gap} flexDirection="column">
519              {block.items.map((item, n) => (
520                <Box flexDirection="row" paddingLeft={item.level * 2}>
521                  <Box width={cellWidth(item.marker) + 1} flexShrink={0}>
522                    <Text color={colors.muted}>{item.marker}</Text>
523                  </Box>
524                  {prose(item.text, `${k}.${n}`, toned)}
525                </Box>
526              ))}
527            </Box>
528          )
529      }
530    })
531
532  const room = Math.max(20, columns)
533  if (!options.document) {
534    return <Box flexDirection="column">{blocks(parseBlocks(markdown), 'md', room)}</Box>
535  }
536  const { fields, body } = splitFrontMatter(markdown)
537  const keyWidth = Math.max(0, ...fields.map(([name]) => cellWidth(name)))
538  return (
539    <Box flexDirection="column">
540      {fields.length > 0 && (
541        <Box flexDirection="column" marginBottom={1} borderStyle="round" borderColor={colors.border} paddingX={1} alignSelf="flex-start">
542          {fields.map(([name, value]) => (
543            <Text>
544              <Text color={colors.muted}>{name + ' '.repeat(keyWidth - cellWidth(name) + 2)}</Text>
545              <Text color={colors.text}>{value}</Text>
546            </Text>
547          ))}
548        </Box>
549      )}
550      {blocks(parseBlocks(body), 'md', room)}
551    </Box>
552  )
553}
554
hooks/diffview.tsx 312 lines
1import type { Elements } from 'claude-code'
2
3import { cellWidth } from './markdown'
4import { mix } from './theme'
5
6// 데스크톱 Code 탭 diff 모양: 줄 전체 폭 연초록·연분홍, 왼쪽 색 세로줄, 번호 한 칸, 추가·삭제 모두 문법 색,
7// 바뀐 단어는 더 진하게, 안 바뀐 구간은 "N unmodified lines" 한 줄로.
8// 엔진 Code 는 색을 바꿀 수 없어 줄마다 배경 Box 를 깔고 그 위에 문법 색만 Code 로 그린다(줄당 Code 하나라 비싸다:
9// 패널은 보이는 행만 그린다). 모든 행 높이가 정해져 있어(줄은 한 행으로 자른다) 행 번호로 위치를 셀 수 있다.
10
11type Els = Elements['terminal']
12
13export type DiffLine = { kind: ' ' | '+' | '-'; text: string; oldNo: number; newNo: number }
14export type Hunk = { oldStart: number; oldLines: number; newStart: number; newLines: number; lines: DiffLine[] }
15
16// 그릴 행: 줄 하나(1행), 또는 안 바뀐 구간 표시(위아래 빈 줄을 포함해 GAP_ROWS 행).
17// 구간은 숨은 첫 줄의 옛·새 번호를 갖는다(누르면 그 자리에 문맥 줄로 편다).
18export type Gap = { kind: 'gap'; count: number; oldStart: number; newStart: number }
19export type DiffRow = { kind: 'line'; line: DiffLine; span?: [number, number] } | Gap
20export const GAP_ROWS = 3
21export const rowHeight = (row: DiffRow) => (row.kind === 'gap' ? GAP_ROWS : 1)
22
23export type DiffPalette = { addBg: string; delBg: string; addStrong: string; delStrong: string; addBar: string; delBar: string; muted: string }
24
25// 틴트는 터미널 바탕에 초록·빨강을 섞어 만든다: 고정 색은 바탕(흰색·회색·짙은 색)에 따라 묻히거나 튄다.
26// 256색으로 그려질 때(엔진이 줄인다)는 섞은 색이 가까운 팔레트 칸으로 뭉개진다: 진한 강조가 바탕과 같은 칸이 되거나
27// 초록이 청록 칸으로 간다. 그래서 xterm 256색 팔레트에 있는 색을 그대로 골라 둔다(줄여도 제자리).
28const PALETTE_256 = {
29  light: { addBg: '#d7ffd7', delBg: '#ffd7d7', addStrong: '#afd7af', delStrong: '#ffafaf', addBar: '#5faf5f', delBar: '#d75f5f' },
30  dark: { addBg: '#005f00', delBg: '#5f0000', addStrong: '#008700', delStrong: '#870000', addBar: '#5fd75f', delBar: '#ff5f5f' },
31} as const
32
33// 엔진이 truecolor 로 그리는지: COLORTERM 이 truecolor·24bit 이고 tmux 밖일 때(tmux 안에서는 FORCE_COLOR=3 이어도 256색으로 줄였다).
34export function isTruecolor(env: { COLORTERM?: string; TMUX?: string }): boolean {
35  return /^(truecolor|24bit)$/i.test(env.COLORTERM ?? '') && !env.TMUX
36}
37
38export function diffPalette(mode: 'light' | 'dark', background: string, muted: string, truecolor = true): DiffPalette {
39  if (!truecolor) return { ...PALETTE_256[mode], muted }
40  const add = mode === 'light' ? '#2da44e' : '#3fb950'
41  const del = mode === 'light' ? '#d1242f' : '#f85149'
42  return {
43    addBg: mix(background, add, 0.16),
44    delBg: mix(background, del, 0.13),
45    addStrong: mix(background, add, 0.38),
46    delStrong: mix(background, del, 0.32),
47    addBar: add,
48    delBar: del,
49    muted,
50  }
51}
52
53const HEADER = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/
54
55// 탭은 네 칸으로 펴 둔다: 조각 폭을 칸 수로 재기 때문. Code 는 탭·줄바꿈 밖의 제어 문자(CRLF 파일의 \r 등)와
56// 10000자 넘는 글을 거절해서 지우고 자른다(한 행으로 잘려 보이므로 뒤는 어차피 안 보인다).
57const LINE_ROOM = 4000
58export const untab = (text: string) => text.replace(/\t/g, '    ').replace(/[\x00-\x08\x0b-\x1f\x7f]/g, '').slice(0, LINE_ROOM)
59
60export function parseHunks(patch: string): Hunk[] {
61  const hunks: Hunk[] = []
62  let current: Hunk | null = null
63  let oldNo = 0
64  let newNo = 0
65  for (const raw of patch.split('\n')) {
66    const header = HEADER.exec(raw)
67    if (header) {
68      oldNo = Number(header[1])
69      newNo = Number(header[3])
70      current = { oldStart: oldNo, oldLines: Number(header[2] ?? 1), newStart: newNo, newLines: Number(header[4] ?? 1), lines: [] }
71      hunks.push(current)
72      continue
73    }
74    if (!current || raw.startsWith('\\')) continue
75    const kind = raw[0] === '+' || raw[0] === '-' ? raw[0] : ' '
76    const text = untab(raw.slice(1))
77    if (kind === '+') current.lines.push({ kind, text, oldNo: 0, newNo: newNo++ })
78    else if (kind === '-') current.lines.push({ kind, text, oldNo: oldNo++, newNo: 0 })
79    else current.lines.push({ kind, text, oldNo: oldNo++, newNo: newNo++ })
80  }
81  return hunks
82}
83
84// 붙어 있는 −줄 묶음과 바로 뒤 +줄 묶음을 차례로 짝지어 바뀐 가운데 구간을 찾는다. 줄 대부분이 바뀌었으면 강조하지 않는다.
85const TOKEN = /\w+|\s+|[^\w\s]/g
86
87export function wordSpan(before: string, after: string): { before: [number, number]; after: [number, number] } | null {
88  const a = before.match(TOKEN) ?? []
89  const b = after.match(TOKEN) ?? []
90  let head = 0
91  while (head < a.length && head < b.length && a[head] === b[head]) head++
92  let tail = 0
93  while (tail < a.length - head && tail < b.length - head && a[a.length - 1 - tail] === b[b.length - 1 - tail]) tail++
94  if (head === 0 && tail === 0) return null
95  const chars = (tokens: string[], from: number, to: number) => tokens.slice(from, to).join('').length
96  const span = (tokens: string[], text: string): [number, number] => [chars(tokens, 0, head), text.length - chars(tokens, tokens.length - tail, tokens.length)]
97  const x = span(a, before)
98  const y = span(b, after)
99  // 바뀐 부분이 없거나(공백만 다름) 줄의 대부분이면 강조가 오히려 시끄럽다.
100  const share = Math.max((x[1] - x[0]) / Math.max(1, before.length), (y[1] - y[0]) / Math.max(1, after.length))
101  if (share > 0.7) return null
102  return { before: x, after: y }
103}
104
105// gaps: 첫 hunk 앞과 hunk 사이의 안 바뀐 줄 수를 행으로 넣을지(패널은 넣고, 대화 속 편집 행은 뺀다).
106export function diffRows(hunks: Hunk[], gaps = true): DiffRow[] {
107  const rows: DiffRow[] = []
108  let oldEnd = 1
109  for (const hunk of hunks) {
110    const skipped = hunk.oldStart - oldEnd
111    if (gaps && hunk.oldStart > 0 && skipped > 0) rows.push({ kind: 'gap', count: skipped, oldStart: oldEnd, newStart: hunk.newStart - skipped })
112    oldEnd = hunk.oldStart + hunk.oldLines
113    const lines = hunk.lines
114    for (let i = 0; i < lines.length; ) {
115      const line = lines[i]
116      if (!line || line.kind !== '-') {
117        if (line) rows.push({ kind: 'line', line })
118        i++
119        continue
120      }
121      // −줄 묶음 뒤 +줄 묶음: 같은 순번끼리 단어 강조를 짝짓는다.
122      let j = i
123      while (lines[j]?.kind === '-') j++
124      let k = j
125      while (lines[k]?.kind === '+') k++
126      const minus = lines.slice(i, j)
127      const plus = lines.slice(j, k)
128      const spans = minus.map((m, n) => (plus[n] ? wordSpan(m.text, plus[n].text) : null))
129      minus.forEach((m, n) => rows.push({ kind: 'line', line: m, ...(spans[n] ? { span: spans[n].before } : {}) }))
130      plus.forEach((p, n) => rows.push({ kind: 'line', line: p, ...(spans[n] ? { span: spans[n].after } : {}) }))
131      i = k
132    }
133  }
134  return rows
135}
136
137// 편 구간: 새 번호로 고른 구간 행을 문맥 줄로 바꾼다. lines 는 그 구간의 줄들(새 파일에서 읽은 것).
138export function openGaps(rows: DiffRow[], opened: ReadonlyMap<number, ReadonlyArray<string>>): DiffRow[] {
139  if (opened.size === 0) return rows
140  return rows.flatMap((row): DiffRow[] => {
141    const lines = row.kind === 'gap' ? opened.get(row.newStart) : undefined
142    if (row.kind !== 'gap' || !lines) return [row]
143    return lines.map((text, index) => ({ kind: 'line', line: { kind: ' ', text, oldNo: row.oldStart + index, newNo: row.newStart + index } }))
144  })
145}
146
147// 그리는 단위: 안 바뀐 구간 표시, 또는 같은 종류(추가·삭제·문맥)로 이어진 줄 덩어리. 덩어리 하나를 배경 Box 하나와
148// 여러 줄 Code 하나로 그려 줄마다 그릴 때보다 요소가 몇 분의 일로 준다(실측: 다시 그리기 4~5배 빠름).
149// 단어 강조가 있는 줄만 홀로 둔다(조각 Code 가 필요하다). 덩어리는 RUN_LINES 줄까지: 창 밖까지 통째로 그리지 않게.
150export type DiffBlock = Gap | { kind: 'lines'; lines: DiffLine[]; span?: [number, number] }
151export const RUN_LINES = 16
152export const blockHeight = (block: DiffBlock) => (block.kind === 'gap' ? GAP_ROWS : block.lines.length)
153
154export function diffBlocks(rows: DiffRow[], max = RUN_LINES): DiffBlock[] {
155  const blocks: DiffBlock[] = []
156  for (const row of rows) {
157    if (row.kind === 'gap') {
158      blocks.push(row)
159      continue
160    }
161    const last = blocks[blocks.length - 1]
162    if (!row.span && last?.kind === 'lines' && !last.span && last.lines.length < max && last.lines[0]?.kind === row.line.kind) last.lines.push(row.line)
163    else blocks.push(row.span ? { kind: 'lines', lines: [row.line], span: row.span } : { kind: 'lines', lines: [row.line] })
164  }
165  return blocks
166}
167
168// 패치 하나의 행과 덩어리: 스크롤할 때마다 패널이 다시 그려지므로 패치 글 기준으로 기억해 둔다.
169const patchCache = new Map<string, { rows: DiffRow[]; blocks: DiffBlock[] }>()
170const PATCH_CACHE = 400
171
172export function patchBlocks(patch: string): { rows: DiffRow[]; blocks: DiffBlock[] } {
173  const hit = patchCache.get(patch)
174  if (hit) return hit
175  const rows = diffRows(parseHunks(patch))
176  const made = { rows, blocks: diffBlocks(rows) }
177  if (patchCache.size >= PATCH_CACHE) patchCache.clear()
178  patchCache.set(patch, made)
179  return made
180}
181
182// 보이는 곳만 그리기: 항목마다 높이가 있을 때, 창(첫 행·보이는 행 수) 앞뒤 한 화면과 always 인 항목만 그리고
183// 나머지 연달은 항목은 높이를 합친 빈 칸 하나로.
184export type WindowStep = { draw: number } | { skip: number }
185
186export function windowPlan(items: ReadonlyArray<{ height: number; always?: boolean }>, offset: number, bodyRows: number): WindowStep[] {
187  const from = offset - bodyRows
188  const to = offset + 2 * bodyRows
189  const steps: WindowStep[] = []
190  let row = 0
191  let skipped = 0
192  items.forEach((item, index) => {
193    const isShown = item.always || (row + item.height > from && row < to)
194    if (isShown) {
195      if (skipped > 0) steps.push({ skip: skipped })
196      skipped = 0
197      steps.push({ draw: index })
198    } else skipped += item.height
199    row += item.height
200  })
201  if (skipped > 0) steps.push({ skip: skipped })
202  return steps
203}
204
205// 번호 칸 폭: 가장 큰 줄 번호 자릿수 + 표시(+/−) + 사이 칸.
206export function gutterWidth(rows: DiffRow[]): number {
207  const most = rows.reduce((max, row) => (row.kind === 'line' ? Math.max(max, row.line.oldNo, row.line.newNo) : max), 0)
208  return String(most).length + 3
209}
210
211// 줄 고르기(댓글): 번호 칸을 줄마다 누를 수 있게 하고, 고른 줄은 mark 색으로 뒤집어 그린다(줄 색으로 뒤집으면 번호가 틴트에 묻힌다).
212// row 는 패치 안 행 번호(first 가 덩어리 첫 줄). 포인터가 올라가면 버튼이 뒤집혀 누를 곳이 보인다.
213export type LinePick = { Button: Els['Button']; first: number; mark: string; isPicked: (row: number) => boolean; onPress: (row: number) => void }
214// 안 바뀐 구간 펴기: 구간 글을 버튼으로(누를 수 있는 파일만, 새 파일 내용을 읽을 수 있는 git 파일).
215export type GapOpen = { Button: Els['Button']; onPress: (gap: Gap) => void }
216type RowOptions = { path?: string; gutter: number; columns: number; unmodified: (count: number) => string; pick?: LinePick; gap?: GapOpen }
217
218const mark = (line: DiffLine) => (line.kind === '+' ? '+' : line.kind === '-' ? '-' : ' ')
219const lineNo = (line: DiffLine) => (line.kind === '-' ? line.oldNo : line.newNo)
220const numberText = (line: DiffLine, gutter: number) => `${String(lineNo(line)).padStart(gutter - 3)} ${mark(line)} `
221
222// 누를 수 있는 번호 칸: 줄마다 버튼 하나(색 있는 번호 글자). 막대 칸의 hover + 는 줄마다 요소가 둘 더 들어 스크롤이 무거워져 뺐다.
223function pickGutter(els: Pick<Els, 'Box' | 'Text'>, pick: LinePick, lines: DiffLine[], key: string, gutter: number, color: string) {
224  const { Box, Text } = els
225  const { Button } = pick
226  return (
227    <Box width={gutter} flexShrink={0} flexDirection="column">
228      {lines.map((line, index) => {
229        const row = pick.first + index
230        const isPicked = pick.isPicked(row)
231        return (
232          <Button key={`${key}.p${index}`} plain onPress={() => pick.onPress(row)}>
233            <Text color={isPicked ? pick.mark : color} inverse={isPicked}>
234              {numberText(line, gutter)}
235            </Text>
236          </Button>
237        )
238      })}
239    </Box>
240  )
241}
242
243// 덩어리 하나. key 는 패널 안에서 겹치지 않게 부르는 쪽이 준다. 높이는 늘 blockHeight 와 같다.
244export function diffBlock(els: Pick<Els, 'Box' | 'Text' | 'Code'>, palette: DiffPalette, block: DiffBlock, key: string, options: RowOptions) {
245  const { Box, Text, Code } = els
246  if (block.kind === 'gap') {
247    const { gap } = options
248    return (
249      <Box key={key} height={GAP_ROWS} flexDirection="column" justifyContent="center">
250        {gap ? (
251          <gap.Button key={`${key}.g`} plain onPress={() => gap.onPress(block)}>
252            <Text color={palette.muted}>{options.unmodified(block.count)}</Text>
253          </gap.Button>
254        ) : (
255          <Text color={palette.muted} wrap="truncate-end">
256            {options.unmodified(block.count)}
257          </Text>
258        )}
259      </Box>
260    )
261  }
262  const { lines } = block
263  const first = lines[0]
264  if (!first) return <Box key={key} />
265  const isAdd = first.kind === '+'
266  const isDel = first.kind === '-'
267  const bg = isAdd ? palette.addBg : isDel ? palette.delBg : undefined
268  const numberColor = isAdd ? palette.addBar : isDel ? palette.delBar : palette.muted
269  const room = Math.max(4, options.columns - 1 - options.gutter)
270  const code = (text: string, codeKey: string) => <Code key={codeKey} source={text === '' ? ' ' : text} path={options.path} wrap="truncate-end" />
271  const body: ReturnType<typeof code>[] = []
272  // 바뀐 단어(한 줄 덩어리): 앞·가운데·뒤 세 조각. 조각마다 폭을 정해야 앞 Code 가 남은 폭을 다 먹지 않는다. 앞부분이 칸을 넘기면 강조를 뺀다.
273  const span = block.span
274  const source = first.text === '' ? ' ' : first.text
275  const pre = span ? cellWidth(source.slice(0, span[0])) : 0
276  const mid = span ? cellWidth(source.slice(span[0], span[1])) : 0
277  if (span && mid > 0 && pre < room) {
278    if (pre > 0) {
279      body.push(
280        <Box key={`${key}.a`} width={pre} flexShrink={0}>
281          {code(source.slice(0, span[0]), `${key}.ac`)}
282        </Box>,
283      )
284    }
285    body.push(
286      <Box key={`${key}.b`} width={Math.min(mid, room - pre)} flexShrink={0} backgroundColor={isAdd ? palette.addStrong : palette.delStrong}>
287        {code(source.slice(span[0], span[1]), `${key}.bc`)}
288      </Box>,
289    )
290    if (pre + mid < room && span[1] < source.length) body.push(code(source.slice(span[1]), `${key}.cc`))
291  } else {
292    // 빈 줄은 공백 하나로: Code 가 빈 줄을 접어 행이 모자라지 않게.
293    body.push(code(lines.map(line => (line.text === '' ? ' ' : line.text)).join('\n'), `${key}.c`))
294  }
295  return (
296    <Box key={key} flexDirection="row" height={lines.length} overflow="hidden" {...(bg ? { backgroundColor: bg } : {})}>
297      {/* 막대는 칸 왼쪽 1/4 만(▎): 칸 전체를 칠하면 데스크탑의 가는 선보다 훨씬 굵어 시선을 끈다. 나머지는 줄 틴트가 비친다. */}
298      <Box width={1} height={lines.length} flexShrink={0}>
299        {isAdd || isDel ? <Text color={isAdd ? palette.addBar : palette.delBar}>{Array(lines.length).fill('▎').join('\n')}</Text> : null}
300      </Box>
301      {options.pick ? (
302        pickGutter(els, options.pick, lines, key, options.gutter, numberColor)
303      ) : (
304        <Box width={options.gutter} flexShrink={0}>
305          <Text color={numberColor}>{lines.map(line => numberText(line, options.gutter)).join('\n')}</Text>
306        </Box>
307      )}
308      {body}
309    </Box>
310  )
311}
312
hooks/comments.ts 66 lines
1import type { CommentDraft, LineComment, LineRef } from '../types'
2import type { DiffLine, DiffRow } from './diffview'
3
4// diff 줄 댓글: 데스크톱 Code 탭처럼 줄(또는 범위)에 남긴 말을 다음 프롬프트에 보이지 않는 context 로 붙인다.
5// 줄은 패치 안 행 번호가 아니라 종류·옛 번호·새 번호로 기억한다: 파일이 더 바뀌어 행이 밀려도 같은 줄을 찾는다.
6export type LinePress = { patch: string; path: string; scope: string; line: DiffLine }
7
8export const lineRef = (line: DiffLine): LineRef => ({ kind: line.kind, oldNo: line.oldNo, newNo: line.newNo })
9const isSame = (a: LineRef, b: LineRef) => a.kind === b.kind && a.oldNo === b.oldNo && a.newNo === b.newNo
10// 화면에 보이는 번호: 지운 줄은 옛 파일, 나머지는 새 파일 번호.
11export const shownNo = (line: LineRef) => (line.kind === '-' ? line.oldNo : line.newNo)
12
13export function rowOf(rows: DiffRow[], ref: LineRef): number {
14  return rows.findIndex(row => row.kind === 'line' && isSame(lineRef(row.line), ref))
15}
16
17// 두 줄 사이(순서 무관)의 행 범위. 둘 중 하나라도 패치에서 사라졌으면 null.
18export function rangeOf(rows: DiffRow[], a: LineRef, b: LineRef): [number, number] | null {
19  const from = rowOf(rows, a)
20  const to = rowOf(rows, b)
21  if (from === -1 || to === -1) return null
22  return from <= to ? [from, to] : [to, from]
23}
24
25export function linesIn(rows: DiffRow[], [from, to]: [number, number]): DiffLine[] {
26  return rows.slice(from, to + 1).flatMap(row => (row.kind === 'line' ? [row.line] : []))
27}
28
29// "61" 또는 "57–61".
30export function rangeLabel(lines: ReadonlyArray<LineRef>): string {
31  const first = lines[0]
32  const last = lines[lines.length - 1]
33  if (!first || !last) return ''
34  const [a, b] = [shownNo(first), shownNo(last)]
35  return a === b ? String(a) : `${a}–${b}`
36}
37
38// 줄 번호를 눌렀을 때: 처음이거나 다른 패치면 그 줄에서 시작, 같은 패치면 범위 끝을 옮긴다.
39// 한 줄만 고른 상태에서 그 줄을 다시 누르면 닫는다.
40export function pressLine(draft: CommentDraft | null, at: LinePress): CommentDraft | null {
41  const ref = lineRef(at.line)
42  if (!draft || draft.patch !== at.patch) return { patch: at.patch, path: at.path, scope: at.scope, anchor: ref, end: ref }
43  if (isSame(ref, draft.anchor) && isSame(draft.end, draft.anchor)) return null
44  return { ...draft, end: ref }
45}
46
47// 입력칸 키: 범위가 바뀌면 입력칸이 다른 자리에 새로 그려지므로 키도 바꾼다. 같은 키면 포커스가 곧 사라질
48// 옛 입력칸에 가서, 다시 그릴 때 프롬프트로 빠진다.
49const refKey = (ref: LineRef) => `${ref.kind === ' ' ? 'c' : ref.kind === '+' ? 'a' : 'd'}${ref.oldNo}.${ref.newNo}`
50export const draftKey = (draft: CommentDraft) => `comment-input-${refKey(draft.anchor)}-${refKey(draft.end)}`
51
52const mark = (line: DiffLine) => (line.kind === ' ' ? ' ' : line.kind)
53
54// 모델이 읽을 블록 하나: 파일:줄, 그 줄들(diff 표시 포함), 댓글. 모델에게 가는 글이라 영어로 둔다.
55export function commentContext(comments: ReadonlyArray<LineComment>): string {
56  const blocks = comments.map(comment => {
57    const width = String(Math.max(...comment.lines.map(shownNo))).length
58    const code = comment.lines.map(line => `${String(shownNo(line)).padStart(width)} ${mark(line)} ${line.text}`).join('\n')
59    return `${comment.path}:${rangeLabel(comment.lines)} (${comment.scope})\n\`\`\`diff\n${code}\n\`\`\`\n${comment.body}`
60  })
61  return [
62    'The user left these comments on lines of a diff in the desk-look diff pane, as part of this message. Removed (-) lines use old-file line numbers; added (+) and unchanged lines use new-file numbers.',
63    ...blocks,
64  ].join('\n\n')
65}
66
hooks/runs.ts 195 lines
1import type { SessionMessage } from 'claude-code'
2
3import type { RunCall, Runs } from '../types'
4
5// $.state 에 도구 출력 전문(Read 파일 내용, 긴 stdout)을 쌓지 않는다. 펼친 행은 30줄 남짓만 보여 준다.
6const LIMIT = 4000
7
8const clip = (text: string) => (text.length > LIMIT ? `${text.slice(0, LIMIT)}\n…` : text)
9
10// 계획(ExitPlanMode)은 길어도 카드에서 펼쳐 읽으므로 넉넉히 둔다.
11const PLAN_LIMIT = 20000
12
13export type PlanSummary = { plan: string | null; filePath?: string }
14
15function outputOf(value: unknown): string | { structuredPatch: unknown[] } | { answers: object } | { agent: AgentSummary } | PlanSummary | undefined {
16  if (value === undefined || value === null) return undefined
17  if (typeof value === 'string') return clip(value)
18  const fields = value as Record<string, unknown>
19  if (typeof fields.stdout === 'string') {
20    return clip([fields.stdout, typeof fields.stderr === 'string' ? fields.stderr : ''].filter(Boolean).join('\n'))
21  }
22  // 편집 결과: 파일 전문(originalFile)은 버리고 실제 줄 번호가 붙은 헌크만 둔다.
23  if (Array.isArray(fields.structuredPatch)) return { structuredPatch: fields.structuredPatch.slice(0, 20) }
24  // 서브에이전트 결과: 카드에 쓸 요약만(결과 글은 앞부분만).
25  const agent = agentOf(fields)
26  if (agent) return { agent }
27  // 계획 결과: 계획 글과 저장된 파일 경로만.
28  const plan = planOf(fields)
29  if (plan) return plan
30  // 질문 결과: 질문 전문은 입력에 있으니 답만 둔다.
31  if (typeof fields.answers === 'object' && fields.answers !== null) return { answers: fields.answers }
32  const file = (fields.file ?? {}) as Record<string, unknown>
33  const content = typeof file.content === 'string' ? file.content : typeof fields.content === 'string' ? fields.content : undefined
34  if (content !== undefined) return clip(content)
35  try {
36    return clip(JSON.stringify(value, null, 2))
37  } catch {
38    return clip(String(value))
39  }
40}
41
42function clipInput(input: Record<string, unknown>): Record<string, unknown> {
43  return Object.fromEntries(Object.entries(input).map(([key, value]) => [key, typeof value === 'string' ? clip(value) : value]))
44}
45
46// 서브에이전트 카드에 쓰는 결과 요약.
47export type AgentSummary = {
48  status: string
49  type?: string
50  model?: string
51  toolUses?: number
52  durationMs?: number
53  tokens?: number
54  added?: number
55  removed?: number
56  text?: string
57}
58
59const AGENT_TEXT = 2000
60const numberOf = (value: unknown) => (typeof value === 'number' ? value : undefined)
61const textOf = (value: unknown) => (typeof value === 'string' ? value : undefined)
62
63// Agent 도구 결과(엔진이 준 그대로, 저장해 둔 요약, JSON 글 어느 것이든)에서 요약을 읽는다. 아니면 null.
64export function agentOf(output: unknown): AgentSummary | null {
65  let value = output
66  if (typeof value === 'string') {
67    try {
68      value = JSON.parse(value)
69    } catch {
70      return null
71    }
72  }
73  if (typeof value !== 'object' || value === null) return null
74  const fields = value as Record<string, unknown>
75  if (typeof fields.agent === 'object' && fields.agent !== null) return fields.agent as AgentSummary
76  if (typeof fields.agentId !== 'string' || typeof fields.status !== 'string') return null
77  const stats = (fields.toolStats ?? {}) as Record<string, unknown>
78  const content = Array.isArray(fields.content) ? (fields.content as Array<Record<string, unknown>>) : []
79  const text = content.map(block => textOf(block.text) ?? '').join('\n').trim()
80  return {
81    status: fields.status,
82    type: textOf(fields.agentType),
83    model: textOf(fields.resolvedModel),
84    toolUses: numberOf(fields.totalToolUseCount),
85    durationMs: numberOf(fields.totalDurationMs),
86    tokens: numberOf(fields.totalTokens),
87    added: numberOf(stats.linesAdded),
88    removed: numberOf(stats.linesRemoved),
89    text: text.length > AGENT_TEXT ? `${text.slice(0, AGENT_TEXT)}…` : text || undefined,
90  }
91}
92
93export const isAgentTool = (tool: string) => tool === 'Agent' || tool === 'Task'
94
95export const isPlanTool = (tool: string) => tool === 'ExitPlanMode'
96
97// ExitPlanMode 결과(엔진이 준 그대로, 저장해 둔 요약, JSON 글, 모델이 받은 결과 글 어느 것이든)에서 계획을 읽는다.
98export function planOf(output: unknown): PlanSummary | null {
99  if (typeof output === 'string') {
100    try {
101      return planOf(JSON.parse(output))
102    } catch {
103      const approved = /##\s*Approved Plan[^\n]*\n([\s\S]+)$/.exec(output)
104      return approved?.[1] ? { plan: approved[1].trim() } : null
105    }
106  }
107  if (typeof output !== 'object' || output === null || !('plan' in output)) return null
108  const fields = output as Record<string, unknown>
109  const plan = typeof fields.plan === 'string' ? fields.plan : null
110  return {
111    plan: plan !== null && plan.length > PLAN_LIMIT ? `${plan.slice(0, PLAN_LIMIT)}\n…` : plan,
112    ...(typeof fields.filePath === 'string' ? { filePath: fields.filePath } : {}),
113  }
114}
115
116type RunKind = 'agent' | 'plan' | 'tool'
117const kindOf = (tool: string): RunKind => (isAgentTool(tool) ? 'agent' : isPlanTool(tool) ? 'plan' : 'tool')
118
119// 답변 텍스트나 사용자 프롬프트가 끼기 전까지 이어진 도구 호출을 한 묶음으로 본다.
120// 데스크톱이 "Ran 2 commands, edited 3 files" 한 줄로 접는 단위와 같다.
121// 서브에이전트는 따로 카드로 그리므로 다른 도구와 섞지 않는다(연달아 띄운 에이전트끼리만 묶는다).
122// 계획(ExitPlanMode)은 늘 혼자 카드 하나다.
123export function computeRuns(messages: ReadonlyArray<SessionMessage>): Runs {
124  const results = new Map<string, { isError: boolean; result: unknown; text: string }>()
125  for (const message of messages) {
126    for (const result of message.toolResults ?? []) {
127      results.set(result.tool_use_id, { isError: result.isError, result: result.result, text: result.text })
128    }
129  }
130
131  const firstOf: Record<string, string> = {}
132  const calls: Record<string, RunCall[]> = {}
133  let current: string | null = null
134  let currentKind: RunKind = 'tool'
135
136  for (const message of messages) {
137    const isPrompt = message.role === 'user' && (message.toolResults ?? []).length === 0 && message.text.trim() !== ''
138    if (isPrompt || (message.role === 'assistant' && message.text.trim() !== '')) {
139      current = null
140    }
141    if (message.role !== 'assistant') continue
142    for (const use of message.toolUses) {
143      const settled = results.get(use.tool_use_id)
144      const output = outputOf(use.result ?? settled?.result ?? settled?.text)
145      const isErrored = use.isError === true || settled?.isError === true
146      const text = settled?.text ?? ''
147      const call: RunCall = {
148        tool_use_id: use.tool_use_id,
149        tool: use.tool,
150        input: clipInput(use.input),
151        isRunning: output === undefined && !isErrored,
152        isErrored,
153        isInterrupted: isErrored && /interrupt/i.test(text),
154        output,
155      }
156      const kind = kindOf(use.tool)
157      if (current !== null && (currentKind !== kind || kind === 'plan')) current = null
158      if (current === null) {
159        current = use.tool_use_id
160        currentKind = kind
161        calls[current] = []
162      }
163      calls[current]?.push(call)
164      firstOf[use.tool_use_id] = current
165    }
166  }
167  return { firstOf, calls }
168}
169
170// 스트림에서 막 온 도구 호출이 들어갈 묶음. computeRuns 와 같은 규칙: 열린 묶음과 종류가 같으면 이어 붙고,
171// 아니면(계획은 늘) 새 묶음을 연다. 답 글이나 프롬프트가 끼면 부르는 쪽이 cursor 를 null 로 닫는다.
172export type RunCursor = { first: string; kind: RunKind } | null
173
174export function placeCall(cursor: RunCursor, id: string, tool: string): { first: string; cursor: RunCursor } {
175  const kind = kindOf(tool)
176  const first = cursor !== null && cursor.kind === kind && kind !== 'plan' ? cursor.first : id
177  return { first, cursor: { first, kind } }
178}
179
180export type PredictedCall = { first: string; call: RunCall }
181
182// 기록에 아직 없는 예측 호출을 묶음에 덧붙인다. 기록에 나온 호출은 기록이 정한 자리를 따른다.
183export function withPredicted(runs: Runs, predicted: ReadonlyArray<PredictedCall>): Runs {
184  const missing = predicted.filter(item => runs.firstOf[item.call.tool_use_id] === undefined)
185  if (missing.length === 0) return runs
186  const firstOf = { ...runs.firstOf }
187  const calls = { ...runs.calls }
188  for (const { first, call } of missing) {
189    const head = firstOf[first] ?? first
190    firstOf[call.tool_use_id] = head
191    calls[head] = [...(calls[head] ?? []), call]
192  }
193  return { firstOf, calls }
194}
195
hooks/agents.ts 200 lines
1import type { AgentInfo, ModelUsage, SessionMessage } from 'claude-code'
2
3import type { AgentDetail, AgentItem, AgentRecord } from '../types'
4import { computeRuns } from './runs'
5import { T } from './i18n'
6
7// 상세에 남길 만큼: 최근 항목 AGENT_ITEMS 개, 글은 항목마다 TEXT_LIMIT 자.
8const AGENT_ITEMS = 200
9const TEXT_LIMIT = 8000
10const clipText = (text: string) => (text.length > TEXT_LIMIT ? `${text.slice(0, TEXT_LIMIT)}\n…` : text)
11
12export const isLive = (status: string) => status === 'pending' || status === 'running' || status === 'waiting'
13
14// 데스크톱이 "69.2k tokens" 로 보이는 값: 마지막 요청이 실은 컨텍스트(입력·캐시·출력 합).
15export const stepTokens = (usage: ModelUsage) =>
16  usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens + usage.output_tokens
17
18// "claude-haiku-5-5" → "Haiku 5.5". 모르는 모양은 그대로.
19export function modelLabel(model: string | undefined): string | undefined {
20  if (!model) return undefined
21  const match = /^claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?:-\d{8})?(\[1m\])?$/.exec(model)
22  if (!match) return model
23  const [, family = '', major, minor] = match
24  return `${family.charAt(0).toUpperCase()}${family.slice(1)} ${minor ? `${major}.${minor}` : major}`
25}
26
27// 데스크톱 카드 끝의 지금 하는 일: Fetching, Searching web …
28export function activityOf(tool: string): string {
29  switch (tool) {
30    case 'WebFetch':
31      return T.actFetching
32    case 'WebSearch':
33      return T.actSearchingWeb
34    case 'Bash':
35    case 'PowerShell':
36      return T.actRunning
37    case 'Read':
38    case 'NotebookRead':
39      return T.actReading
40    case 'Edit':
41    case 'MultiEdit':
42    case 'Write':
43    case 'NotebookEdit':
44      return T.actEditing
45    case 'Grep':
46    case 'Glob':
47    case 'LS':
48    case 'ToolSearch':
49      return T.actSearching
50    case 'Agent':
51    case 'Task':
52      return T.actDelegating
53    default:
54      return T.actUsingTool
55  }
56}
57
58// 엔진 목록을 기록에 합친다: 이름·종류·상태는 목록이 정본, 수치는 기록이 가진 것을 둔다.
59// 목록에서 사라진 것(끝난 지 좀 된 에이전트)은 기록 그대로 남는다. 엔진은 도는 에이전트를 빼지 않으므로,
60// 목록에 있다가 사라졌는데 기록이 아직 도는 중이면 끝을 놓친 것(도중의 /reload-plugins 등)이라 끝난 것으로 둔다.
61export function mergeAgents(records: Readonly<Record<string, AgentRecord>>, list: ReadonlyArray<AgentInfo>, now: number): Record<string, AgentRecord> {
62  const next = { ...records }
63  for (const info of list) {
64    const old = next[info.id]
65    const isEnded = !isLive(info.status)
66    next[info.id] = {
67      toolUses: 0,
68      startedAt: now,
69      ...old,
70      id: info.id,
71      description: info.description || old?.description || info.type,
72      type: info.type,
73      status: info.status,
74      ...(info.name ? { name: info.name } : {}),
75      listed: true,
76      // 한 번의 실행이 끝나도(turn.complete) 엔진이 아직 살아 있다고 하면 시간은 계속 간다.
77      // 다시 돌기 시작하면(SendMessage 로 이어 받은 에이전트) 목록에서 뺀 것도 되돌린다.
78      ...(isEnded ? { endedAt: old?.endedAt ?? now, activity: undefined } : { endedAt: undefined, dismissed: undefined }),
79    }
80  }
81  const present = new Set(list.map(info => info.id))
82  for (const agent of Object.values(next)) {
83    if (agent.listed && !present.has(agent.id) && isLive(agent.status)) {
84      next[agent.id] = { ...agent, status: 'completed', endedAt: agent.endedAt ?? now, activity: undefined }
85    }
86  }
87  return next
88}
89
90// 목록 순서: 도는 것 먼저, 그 안에서는 늦게 시작한 것이 위. 목록에서 뺀 끝난 작업은 보이지 않는다.
91export function orderAgents(records: Readonly<Record<string, AgentRecord>>): { live: AgentRecord[]; done: AgentRecord[] } {
92  const all = Object.values(records).sort((a, b) => (b.startedAt ?? 0) - (a.startedAt ?? 0))
93  return { live: all.filter(agent => isLive(agent.status)), done: all.filter(agent => !isLive(agent.status) && !agent.dismissed) }
94}
95
96// 끝난 작업을 목록에서 뺀다(ids 를 안 주면 끝난 것 모두). 도는 작업은 그대로 둔다.
97export function dismissAgents(records: Readonly<Record<string, AgentRecord>>, ids?: ReadonlyArray<string>): Record<string, AgentRecord> {
98  const next = { ...records }
99  for (const agent of Object.values(records)) {
100    if (!isLive(agent.status) && (ids === undefined || ids.includes(agent.id))) next[agent.id] = { ...agent, dismissed: true }
101  }
102  return next
103}
104
105// 에이전트 대화를 상세 화면 차례로: 첫 사용자 메시지는 지시, 그 뒤는 답변 글·도구 묶음·사용자 메시지.
106// 서브에이전트가 보고를 넘기는 도구. 데스크톱처럼 도구 줄이 아니라 답변 글로 보인다.
107const HANDBACK = 'SubagentHandback'
108
109const handbackOf = (input: Record<string, unknown>) => (typeof input.message === 'string' ? input.message.trim() : '')
110
111export function agentDetailOf(id: string, messages: ReadonlyArray<SessionMessage>): AgentDetail {
112  const reports = messages.map(message => message.toolUses.filter(use => use.tool === HANDBACK).map(use => handbackOf(use.input)))
113  const plain = messages.map(message => ({ ...message, toolUses: message.toolUses.filter(use => use.tool !== HANDBACK) }))
114  const runs = computeRuns(plain)
115  const items: AgentItem[] = []
116  let prompt = ''
117  plain.forEach((message, index) => {
118    if (message.role === 'user') {
119      const isPrompt = (message.toolResults ?? []).length === 0 && message.text.trim() !== ''
120      if (!isPrompt) return
121      if (index === 0) prompt = clipText(message.text.trim())
122      else items.push({ kind: 'user', text: clipText(message.text.trim()) })
123      return
124    }
125    if (message.text.trim() !== '') items.push({ kind: 'text', text: clipText(message.text.trim()) })
126    for (const use of message.toolUses) {
127      if (runs.firstOf[use.tool_use_id] === use.tool_use_id) {
128        items.push({ kind: 'run', id: use.tool_use_id, calls: runs.calls[use.tool_use_id] ?? [] })
129      }
130    }
131    for (const report of reports[index] ?? []) if (report !== '') items.push({ kind: 'text', text: clipText(report) })
132  })
133  return { id, prompt, items: items.slice(-AGENT_ITEMS) }
134}
135
136// 백그라운드로 넘어간 셸(Bash 결과의 backgroundTaskId)이나 모니터(Monitor 결과의 taskId)를 기록 한 줄로.
137// run_in_background 뿐 아니라 Ctrl+B·시간 초과로 넘어간 명령도 결과에 id 가 있다.
138export function backgroundTaskOf(tool: string, input: Record<string, unknown>, result: unknown, startedAt: number): AgentRecord | null {
139  const fields = typeof result === 'object' && result !== null ? (result as Record<string, unknown>) : {}
140  const text = (value: unknown) => (typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined)
141  const command = text(input.command)
142  if (tool === 'Bash' && typeof fields.backgroundTaskId === 'string') {
143    return { id: fields.backgroundTaskId, kind: 'shell', description: text(input.description) ?? command ?? 'shell', type: 'shell', status: 'running', command, startedAt, toolUses: 0 }
144  }
145  if (tool === 'Monitor' && typeof fields.taskId === 'string') {
146    return { id: fields.taskId, kind: 'monitor', description: text(input.description) ?? command ?? 'monitor', type: 'monitor', status: 'running', command, startedAt, toolUses: 0 }
147  }
148  return null
149}
150
151// 백그라운드로 넘긴 Bash 의 결과 글("… Output is being written to: /tmp/…/tasks/<id>.output")에서 출력 파일.
152// 끝남 알림을 기다리지 않고 도는 동안 끝 줄을 읽으려고.
153export function outputFileOf(text: unknown): string | undefined {
154  return typeof text === 'string' ? /written to:?\s*(\S+\.output)\b/.exec(text)?.[1] : undefined
155}
156
157export type TaskNotice = { id: string; status?: string; outputFile?: string; summary?: string }
158
159// 작업이 끝났다는 알림 글(<task-notification> 묶음, 여러 개일 수 있다)에서 id·상태·출력 파일·요약을 읽는다.
160// 모니터의 30분 만료는 <status> 없이 <event>[Monitor expired …]</event> 로만 알리므로 끝남(completed)으로 읽는다.
161// 지난 세션에서 끝나지 못한 작업들은 <task-id> 여럿(+ __orphan_summary__ 표지)을 한 묶음으로 알린다.
162const EXPIRED = /^\[Monitor expired\b/
163
164export function parseNotices(text: string): TaskNotice[] {
165  const tag = (block: string, name: string) => new RegExp(`<${name}>([\\s\\S]*?)</${name}>`).exec(block)?.[1]?.trim()
166  return [...text.matchAll(/<task-notification>([\s\S]*?)<\/task-notification>/g)].flatMap(match => {
167    const block = match[1] ?? ''
168    const ids = [...block.matchAll(/<task-id>([\s\S]*?)<\/task-id>/g)].map(found => found[1]?.trim() ?? '').filter(id => id !== '' && !id.startsWith('__'))
169    const event = tag(block, 'event')
170    const status = tag(block, 'status') ?? (event !== undefined && EXPIRED.test(event) ? 'completed' : undefined)
171    const outputFile = tag(block, 'output-file')
172    const summary = tag(block, 'summary')
173    return ids.map(id => ({ id, ...(status ? { status } : {}), ...(outputFile ? { outputFile } : {}), ...(summary ? { summary } : {}) }))
174  })
175}
176
177// 알림을 기록에 반영한다. 끝난 상태(completed·failed·killed 등)면 끝난 시각을 적는다. 모르는 id 는 건너뛴다.
178export function applyNotices(records: Readonly<Record<string, AgentRecord>>, notices: ReadonlyArray<TaskNotice>, now: number): Record<string, AgentRecord> {
179  const next = { ...records }
180  for (const notice of notices) {
181    const task = next[notice.id]
182    if (!task) continue
183    const status = notice.status && !isLive(notice.status) ? notice.status : task.status
184    next[notice.id] = {
185      ...task,
186      status,
187      ...(notice.outputFile ? { outputFile: notice.outputFile } : {}),
188      ...(notice.summary ? { summary: notice.summary } : {}),
189      ...(!isLive(status) ? { endedAt: task.endedAt ?? now, activity: undefined } : {}),
190    }
191  }
192  return next
193}
194
195// 출력의 마지막 lines 줄(앞에 잘린 줄 수).
196export function tailOf(text: string, lines: number): string {
197  const all = text.replace(/\n+$/, '').split('\n')
198  return all.length > lines ? `${T.moreLines(all.length - lines)}\n${all.slice(-lines).join('\n')}` : all.join('\n')
199}
200
hooks/sessions.ts 100 lines
1import type { LiveSession, SessionEntry } from '../types'
2import { cellWidth } from './markdown'
3import { T } from './i18n'
4
5// ~/.claude/projects/<프로젝트>/<세션>.jsonl 하나에서 세션 줄 하나. 작업 폴더는 파일 앞(head)의 첫 값,
6// 사용자가 붙인 제목·자동 제목·마지막 프롬프트는 파일 끝(tail)의 마지막 값을 쓴다(기록 파일은 수십 MB 까지 커진다).
7// 제목도 프롬프트도 없는 세션은 대화가 한 번도 없었던 빈 세션이라 null.
8export function sessionOf(id: string, updatedAt: number, head: string, tail: string): SessionEntry | null {
9  if (!/^[0-9a-f-]{36}$/.test(id)) return null
10  const field = (key: string) => new RegExp(`"${key}":"([^"]*)"`, 'g')
11  const last = (key: string) => [...tail.matchAll(field(key))].at(-1)?.[1] ?? ''
12  const title = last('customTitle') || last('aiTitle') || last('lastPrompt').slice(0, 120)
13  if (!title) return null
14  return { id, updatedAt, cwd: field('cwd').exec(head)?.[1] ?? '', title }
15}
16
17// 패널에 그리는 순서(묶음 순서)대로 번호를 매긴다. 현재 세션은 번호 없이 ● 로 그리므로 뺀다.
18// `/desk-sessions <번호>` 가 이 순서를 쓴다.
19export function numbered(list: SessionEntry[], currentCwd: string, perGroup: number, currentId = ''): SessionEntry[] {
20  return groupSessions(list, currentCwd)
21    .flatMap(group => group.sessions.slice(0, perGroup))
22    .filter(entry => entry.id !== currentId)
23}
24
25// 프로젝트(작업 폴더)별로 묶는다. 현재 폴더가 맨 위, 나머지는 최근 활동 순.
26export function groupSessions(list: SessionEntry[], currentCwd: string): Array<{ cwd: string; sessions: SessionEntry[] }> {
27  const groups = new Map<string, SessionEntry[]>()
28  for (const entry of list) {
29    const key = entry.cwd || T.unknownFolder
30    groups.set(key, [...(groups.get(key) ?? []), entry])
31  }
32  return [...groups]
33    .map(([cwd, sessions]) => ({ cwd, sessions }))
34    .sort((a, b) => (a.cwd === currentCwd ? -1 : b.cwd === currentCwd ? 1 : 0))
35}
36
37export function ago(at: number, now: number): string {
38  const minutes = Math.max(0, Math.floor((now - at) / 60_000))
39  if (minutes < 1) return T.justNow
40  if (minutes < 60) return T.minutesShort(minutes)
41  const hours = Math.floor(minutes / 60)
42  if (hours < 24) return T.hoursShort(hours)
43  return T.daysShort(Math.floor(hours / 24))
44}
45
46// 칸 수 기준으로 자르고 말줄임표를 붙인다.
47export function clip(text: string, width: number): string {
48  if (cellWidth(text) <= width) return text
49  let out = ''
50  for (const ch of text) {
51    if (cellWidth(out + ch) > width - 1) break
52    out += ch
53  }
54  return `${out}…`
55}
56
57// 검색: 띄어 쓴 낱말이 모두 제목이나 폴더에 들어 있는 세션만(대소문자 무시).
58export function filterSessions(list: SessionEntry[], query: string): SessionEntry[] {
59  const words = query.toLowerCase().split(/\s+/).filter(Boolean)
60  if (words.length === 0) return list
61  return list.filter(entry => {
62    const hay = `${entry.title} ${entry.cwd}`.toLowerCase()
63    return words.every(word => hay.includes(word))
64  })
65}
66
67// `claude agents --json` 에서 지금 떠 있는(pid 있는) 세션만, 세션 id 로. 끝난 백그라운드 세션은 pid 가 없다.
68export function liveSessionsOf(json: string): Record<string, LiveSession> {
69  let rows: unknown
70  try {
71    rows = JSON.parse(json)
72  } catch {
73    return {}
74  }
75  if (!Array.isArray(rows)) return {}
76  const live: Record<string, LiveSession> = {}
77  for (const row of rows as Array<Record<string, unknown>>) {
78    if (typeof row.pid !== 'number' || typeof row.sessionId !== 'string') continue
79    const status = row.status === 'busy' || row.status === 'waiting' ? row.status : 'idle'
80    live[row.sessionId] = { kind: row.kind === 'background' ? 'background' : 'interactive', job: typeof row.id === 'string' ? row.id : null, status }
81  }
82  return live
83}
84
85// 묶음을 접었는지: 사람이 고른 값이 없으면 지금 폴더만 펴 둔다.
86export const isGroupFolded = (folds: Record<string, boolean>, cwd: string, currentCwd: string) => folds[`sessions:fold:${cwd}`] ?? cwd !== currentCwd
87
88// `herdr pane list` 에서 그 세션이 열린 패널의 작업공간·탭. herdr 의 claude 연동이 세션을 시작할 때 알린 id 로 찾는다.
89export function herdrPaneOf(json: string, sessionId: string): { workspace: string; tab: string } | null {
90  let panes: unknown
91  try {
92    panes = (JSON.parse(json) as { result?: { panes?: unknown } }).result?.panes
93  } catch {
94    return null
95  }
96  if (!Array.isArray(panes)) return null
97  const pane = (panes as Array<Record<string, unknown>>).find(item => (item.agent_session as { value?: unknown } | undefined)?.value === sessionId)
98  return pane && typeof pane.workspace_id === 'string' && typeof pane.tab_id === 'string' ? { workspace: pane.workspace_id, tab: pane.tab_id } : null
99}
100
hooks/ask.tsx 202 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { AskQuestion, AskState } from '../types'
5import { T } from './i18n'
6
7// 질문 카드: AskUserQuestion 을 엔진 창 대신 입력창 위 띠의 카드로 묻는다(데스크톱과 같은 자리).
8// 도구 호출 훅이 답을 기다리며 결과를 직접 돌려주고, 엔진은 그 결과를 도구의 원래 변환기로 모델에게 넘긴다.
9// 입력창이 비어 있으면 숫자 키가 띠의 버튼을 바로 누른다: 1-8 선택지, 0 제출(여러 개 고르기), 9 엔진 창.
10// 터미널 말고 다른 화면이 붙은 세션은 엔진 창 그대로. Remote Control 세션은 아래 REMOTE 참고.
11// 엔진 창은 뜰 때 알림(permission_prompt)을 보내지만 카드는 도구가 도는 중이라 엔진이 보내지 않는다. 그래서 카드가 직접 알린다(askNotify).
12
13type On = Parameters<Register>[0]
14
15const asking = atom({ plugin: 'desk-look', key: 'ask' } as const, null as AskState | null)
16const promptOrigin = atom({ plugin: 'desk-look', key: 'promptOrigin' } as const, null as 'composer' | 'bridge' | null)
17
18// 훅은 자기 코드 시간 10초 안에 끝나야 하지만, 엔진 호출($)을 기다리는 동안은 시계가 멈춘다($.clock.sleep 은 예외라 못 쓴다).
19// 그래서 임시 폴더에 이름 있는 파이프(answer)를 만들고 cat 으로 읽으며 기다린다. 카드 버튼이 tee 로 답을 써 넣으면 cat 이 끝난다.
20// process.run 은 한 번에 10분까지라, WAIT_ROUND_S 초(9분)마다 시간이 다 돼 끊기면 다시 기다린다.
21// 셸은 쓰지 않는다: 디렉터리 검사가 셸·인라인 스크립트를 리뷰어에게 넘긴다.
22const WAIT_ROUND_S = 540
23const WAIT_ROUNDS = 40
24// 카드를 건드렸다는 표시(touched 파일). 기다리는 도구 훅은 그동안 바뀐 상태를 읽지 못해(훅이 시작할 때 값을 본다) 파일로 알린다.
25// 버튼이 매번 다른 글을 써서, 훅은 글이 바뀌었는지로 안다.
26// Remote Control(Claude 앱)은 surfaces() 에 잡히지 않는다(앱이 attach 하지 않는다). 카드를 띄우면 엔진이
27// 원격 응답 요청을 보내지 않아 앱에서 답할 수 없다. 그래서 마지막 사람 입력이 앱에서 왔으면 엔진 창이고,
28// 세션 상태 파일에 bridgeSessionId 가 있으면 마지막 사람 입력이 터미널에서 왔을 때만 카드를 띄우고, 카드를 HANDOVER_MS 동안 아무도 건드리지 않으면
29// (자리를 떠 앱으로 보는 중) 엔진 창에 넘겨 앱에도 묻게 한다. 그동안은 HANDOVER_ROUND_S 초마다 돌아와 살핀다.
30export const HANDOVER_MS = 60_000
31const HANDOVER_ROUND_S = 5
32
33// 세션 상태 파일(~/.claude/sessions/*.json) 하나가 이 세션의 것이고 Remote Control 이 붙어 있는지.
34export function isBridgedRecord(text: string, sessionId: string): boolean {
35  return sessionId !== '' && text.includes(`"sessionId":"${sessionId}"`) && text.includes('"bridgeSessionId":"')
36}
37
38export type AskReply =
39  | { kind: 'answer'; answers: Record<string, string> }
40  | { kind: 'engine' }
41  | { kind: 'dismiss' }
42  | { kind: 'cancel' }
43
44const str = (value: unknown) => (typeof value === 'string' ? value : undefined)
45const num = (value: unknown) => (typeof value === 'number' ? value : undefined)
46
47// 도구 입력을 읽는다. 그릴 수 없는 질문이 하나라도 있으면 null(엔진 창).
48// 미리보기(preview)는 선택지에 마우스를 올리면 카드 아래에 보인다.
49export function parseQuestions(value: unknown): AskQuestion[] | null {
50  if (!Array.isArray(value) || value.length === 0) return null
51  const out: AskQuestion[] = []
52  for (const raw of value as Array<Record<string, unknown>>) {
53    const question = str(raw?.question)
54    if (!question) return null
55    const kind = raw.kind === 'text' || raw.kind === 'number' ? raw.kind : 'choice'
56    const options = Array.isArray(raw.options) ? (raw.options as Array<Record<string, unknown>>) : []
57    if (kind === 'choice' && options.length === 0) return null
58    out.push({
59      question,
60      header: str(raw.header) ?? '',
61      kind,
62      description: str(raw.description),
63      options: options.map(option => ({ label: str(option.label) ?? '', description: str(option.description), preview: str(option.preview) })),
64      multiSelect: raw.multiSelect === true,
65      placeholder: str(raw.placeholder),
66      min: num(raw.min),
67      max: num(raw.max),
68      unit: str(raw.unit),
69    })
70  }
71  return out
72}
73
74// 한 질문의 답: 직접 입력한 글이 있으면 그것(여러 개 고르기면 고른 것 뒤에), 아니면 고른 라벨.
75export function answerOf(question: AskQuestion, picks: readonly string[], text: string): string {
76  const typed = text.trim()
77  if (question.kind !== 'choice') return typed
78  // 여러 개 고르기는 누른 순서가 아니라 선택지 순서로(엔진 창과 같게)
79  const ordered = question.options.map(option => option.label).filter(label => picks.includes(label))
80  if (question.multiSelect) return [...ordered, ...(typed ? [typed] : [])].join(', ')
81  return typed || picks[0] || ''
82}
83
84// 숫자 답 검사: 틀리면 이유, 맞으면 null.
85export function numberProblem(question: AskQuestion, text: string): string | null {
86  if (question.kind !== 'number') return null
87  const value = Number(text.trim())
88  if (text.trim() === '' || !Number.isFinite(value)) return T.needNumber
89  if (question.min !== undefined && value < question.min) return T.atLeast(question.min)
90  if (question.max !== undefined && value > question.max) return T.atMost(question.max)
91  return null
92}
93
94// 기다리는 cat 에 답을 넘긴다(register.tsx 의 replyAsk 와 같다: $ 는 파일을 넘지 못한다).
95async function reply($: EngineInterface, dir: string, payload: AskReply) {
96  await $.process.run(['tee', `${dir}/answer`], { stdin: JSON.stringify(payload), timeoutMs: 3000 })
97}
98
99async function isBridged($: EngineInterface, sessionId: string): Promise<boolean> {
100  const [configDir, home] = await Promise.all([$.env.get('CLAUDE_CONFIG_DIR'), $.env.get('HOME')])
101  const base = configDir || (home ? `${home}/.claude` : '')
102  if (!base || sessionId === '') return false
103  for (const entry of await $.fs.list(`${base}/sessions`).catch(() => [])) {
104    if (entry.kind !== 'file' || !entry.name.endsWith('.json')) continue
105    if (isBridgedRecord(await $.fs.read(`${base}/sessions/${entry.name}`).catch(() => ''), sessionId)) return true
106  }
107  return false
108}
109
110// 알림 본문: 첫 질문, 여러 개면 "외 N개".
111export function askNotice(questions: readonly AskQuestion[]): string {
112  const first = questions[0]?.question ?? ''
113  return questions.length > 1 ? T.moreQuestions(first, questions.length - 1) : first
114}
115
116export function registerAsk(on: On, notify: boolean) {
117  on('tool.call', { tool: 'AskUserQuestion' }, async ($, e, next) => {
118    const questions = parseQuestions(e.questions)
119    if (questions === null) return next(e)
120    const surfaces = await $.session.surfaces()
121    if (surfaces.length !== 1 || surfaces[0] !== 'terminal') return next(e)
122    if ((await read($, asking)) !== null) return next(e)
123    // 앱(bridge)에서 온 입력이면 세션 상태 파일 없이도 Remote Control 이다. 파일은 엔진이 지우기도 한다.
124    const origin = await read($, promptOrigin)
125    if (origin === 'bridge') return next(e)
126    const sessionId = await $.session.id().catch(() => '')
127    const isRemote = await isBridged($, sessionId).catch(() => false)
128    if (isRemote && origin !== 'composer') return next(e)
129
130    const made = await $.process.run(['mktemp', '-d'], { timeoutMs: 3000 }).catch(() => null)
131    const dir = made?.exitCode === 0 ? made.stdout.trim() : ''
132    if (dir === '') return next(e)
133    const piped = await $.process.run(['mkfifo', `${dir}/answer`], { timeoutMs: 3000 }).catch(() => null)
134    if (piped?.exitCode !== 0) {
135      await $.process.run(['rm', '-rf', dir], { timeoutMs: 3000 }).catch(() => undefined)
136      return next(e)
137    }
138    const id = e.tool_use_id ?? dir
139    const shownAt = await $.clock.now()
140    await update($, asking, () => ({ id, dir, questions, step: 0, picks: questions.map(() => []), texts: questions.map(() => ''), shownAt }))
141    if (notify) {
142      void $.ui.notify(askNotice(questions), { title: T.askTitle }).catch(() => undefined)
143    }
144
145    // 턴을 중단하면(Esc) 기다리던 cat 을 끝낸다.
146    const onAbort = () => void reply($, dir, { kind: 'cancel' }).catch(() => undefined)
147    next.signal.addEventListener('abort', onAbort)
148    const roundS = isRemote ? HANDOVER_ROUND_S : WAIT_ROUND_S
149    const rounds = Math.ceil((WAIT_ROUNDS * WAIT_ROUND_S) / roundS)
150    let touchedAt = shownAt
151    let touch = ''
152    let isHandedOver = false
153    let answered = ''
154    for (let round = 0; round < rounds && !next.signal.aborted; round++) {
155      const startedAt = await $.clock.now()
156      // 시간이 다 되면 cat 이 죽고 호출은 거절된다(null): 한 바퀴가 끝난 것
157      const ran = await $.process.run(['cat', `${dir}/answer`], { timeoutMs: roundS * 1000 }).catch(() => null)
158      if (ran !== null && ran.exitCode === 0 && ran.stdout.trim() !== '') {
159        answered = ran.stdout
160        break
161      }
162      const now = await $.clock.now()
163      // 기다리지 못하고 곧바로 끝났으면(파이프가 사라졌다) 헛돌지 않고 엔진 창에 넘긴다
164      if (now - startedAt < 1000) {
165        isHandedOver = true
166        break
167      }
168      if (!isRemote) continue
169      const touched = await $.fs.read(`${dir}/touched`).catch(() => '')
170      if (touched !== touch) {
171        touch = touched
172        touchedAt = now
173      } else if (now - touchedAt >= HANDOVER_MS) {
174        isHandedOver = true
175        break
176      }
177    }
178    next.signal.removeEventListener('abort', onAbort)
179    await update($, asking, () => null)
180    await $.process.run(['rm', '-rf', dir], { timeoutMs: 3000 }).catch(() => undefined)
181    if (isHandedOver) return next(e)
182
183    let answer: AskReply = { kind: 'cancel' }
184    try {
185      answer = JSON.parse(answered) as AskReply
186    } catch {
187      answer = { kind: 'cancel' }
188    }
189    switch (answer.kind) {
190      case 'answer':
191        return { result: { questions: e.questions, answers: answer.answers } }
192      case 'engine':
193        return next(e)
194      case 'dismiss':
195        return { deny: 'The user closed the question without answering.' }
196      case 'cancel':
197        return { deny: 'The question was cancelled before the user answered.' }
198    }
199  })
200}
201
202
hooks/gather.ts 65 lines
1import type { Chunk, HookStream, TurnStepResult } from 'claude-code'
2
3// 답 글을 블록째 보여주기(설정 replyInBlocks). 엔진은 글 청크를 100ms 마다 흘려 그리는데, 이 훅은 한 글 블록의
4// 청크를 붙잡았다가 블록이 끝날 때(다른 블록·도구·멈춤 청크, 스트림 끝) 한꺼번에 내보낸다. 엔진이 transcript 에
5// 한 줄씩 적는 단위와 같다. 순서는 바꾸지 않고 늦추기만 한다.
6// 긴 블록을 화면 몫만큼 먼저 내보내던 판(0.51)은 "한 덩어리 나오고 아무 표시 없이 기다리다 또 한 덩어리"가 되어 걷었다:
7// 글이 보이면 엔진이 스피너를 걷어 덩어리 사이 대기를 알릴 곳이 없다. 다 찰 때까지 스피너가 줄 수를 보이고, 대신
8// 화면보다 긴 답은 엔진이 끝으로 따라 내려가 앞부분은 올려서 읽는다.
9
10type StepChunk = Chunk<'turn.step'>
11
12let gathered = 0
13
14// 지금 붙잡고 있는 글의 줄 수(스피너가 보여 준다). 0 이면 붙잡은 글이 없다.
15export function gatheredLines(): number {
16  return gathered
17}
18
19// 메인 대화 한 단계의 스트림을 받아 글 청크를 블록째 모아 내보낸다. 끝까지 읽은 결과를 그대로 돌려준다.
20// settle: 마지막 블록을 내보낸 뒤 멈춤 청크 전에 기다리는 일. 엔진은 글을 100ms 마다 묶어 그려서, 블록과 멈춤이
21// 한 묶음에 들어가면 진행 중 글을 한 번도 그리지 않은 채 스피너를 먼저 걷고, 확정된 글은 그 뒤에야 나와 빈 화면이 낀다.
22export async function* gather(stream: HookStream<StepChunk, TurnStepResult>, settle: () => Promise<void>): AsyncGenerator<StepChunk, TurnStepResult> {
23  let held: StepChunk[] = []
24  let block: number | null = null
25  const release = () => {
26    const out = held
27    held = []
28    block = null
29    gathered = 0
30    return out
31  }
32  try {
33    while (true) {
34      const step = await stream.next()
35      if (step.done === true) {
36        yield* release()
37        return step.value
38      }
39      const chunk = step.value
40      if (chunk.kind === 'engine' && block !== null) {
41        // 블록 시작·끝 표시는 붙잡은 글과 같은 순서로 내보낸다
42        held.push(chunk)
43        continue
44      }
45      const ended = chunk.kind === 'stop' && block !== null
46      if (chunk.kind !== 'text' || (block !== null && chunk.index !== block)) yield* release()
47      if (ended) await settle()
48      if (chunk.kind !== 'text') {
49        yield chunk
50        continue
51      }
52      if (block === null) gathered = 1
53      block = chunk.index
54      held.push(chunk)
55      gathered += chunk.text.split('\n').length - 1
56    }
57  } catch (error) {
58    // 중단·오류: 붙잡은 글을 버리지 않고 내보낸 뒤 그대로 던진다
59    yield* release()
60    throw error
61  } finally {
62    gathered = 0
63  }
64}
65
hooks/tasks.ts 81 lines
1import type { SessionMessage } from 'claude-code'
2
3import type { TaskItem } from '../types'
4
5type Status = TaskItem['status']
6
7const STATUSES = new Set<Status>(['pending', 'in_progress', 'completed'])
8
9const str = (value: unknown) => (typeof value === 'string' ? value : undefined)
10const status = (value: unknown): Status | undefined => (STATUSES.has(value as Status) ? (value as Status) : undefined)
11
12// 세션 기록에서 지금의 할 일 목록을 다시 세운다. 데스크톱의 계획 카드와 같은 내용이다.
13// TodoWrite 는 목록 전체를 바꾸고, TaskCreate 는 하나를 더하고, TaskUpdate 는 고치거나(deleted 면) 지운다.
14// TaskList 의 결과는 그 시점의 정답이라 상태를 거기에 맞춘다. 실패한 호출은 건너뛴다.
15export function computeTasks(messages: ReadonlyArray<SessionMessage>): TaskItem[] {
16  const results = new Map<string, { isError: boolean; result: unknown }>()
17  for (const message of messages) {
18    for (const result of message.toolResults ?? []) {
19      results.set(result.tool_use_id, { isError: result.isError, result: result.result })
20    }
21  }
22
23  let list: TaskItem[] = []
24  for (const message of messages) {
25    if (message.role !== 'assistant') continue
26    for (const use of message.toolUses) {
27      const settled = results.get(use.tool_use_id)
28      if (use.isError === true || settled?.isError === true) continue
29      const output = (use.result ?? settled?.result ?? {}) as Record<string, unknown>
30      const input = use.input
31      switch (use.tool) {
32        case 'TodoWrite': {
33          const todos = Array.isArray(input.todos) ? (input.todos as Array<Record<string, unknown>>) : []
34          list = todos.map((todo, index) => ({
35            id: `todo-${index}`,
36            subject: str(todo.content) ?? '',
37            status: status(todo.status) ?? 'pending',
38            activeForm: str(todo.activeForm),
39          }))
40          break
41        }
42        case 'TaskCreate': {
43          const task = (output.task ?? {}) as Record<string, unknown>
44          const id = str(task.id) ?? String(list.length + 1)
45          list = [...list, { id, subject: str(input.subject) ?? str(task.subject) ?? '', status: 'pending', activeForm: str(input.activeForm) }]
46          break
47        }
48        case 'TaskUpdate': {
49          const id = str(input.taskId)
50          if (input.status === 'deleted') {
51            list = list.filter(item => item.id !== id)
52            break
53          }
54          list = list.map(item =>
55            item.id === id
56              ? {
57                  ...item,
58                  subject: str(input.subject) ?? item.subject,
59                  status: status(input.status) ?? item.status,
60                  activeForm: str(input.activeForm) ?? item.activeForm,
61                }
62              : item,
63          )
64          break
65        }
66        case 'TaskList': {
67          const tasks = Array.isArray(output.tasks) ? (output.tasks as Array<Record<string, unknown>>) : null
68          if (tasks === null) break
69          list = tasks.map(task => {
70            const id = str(task.id) ?? ''
71            const known = list.find(item => item.id === id)
72            return { id, subject: str(task.subject) ?? known?.subject ?? '', status: status(task.status) ?? 'pending', activeForm: known?.activeForm }
73          })
74          break
75        }
76      }
77    }
78  }
79  return list.filter(item => item.subject !== '')
80}
81
hooks/activity.ts 302 lines
1import type { SessionMessage } from 'claude-code'
2
3import type { ActivityEvent, ActivityKind, ActivityLog, TaskItem } from '../types'
4import { cellWidth } from './markdown'
5
6// 입력창 위 진행 띠: 할 일 단계 한 줄과 지금 도는 일 한 줄. 모델에게 따로 신고를 받지 않고
7// 도구 호출·할 일 목록·도구가 띄운 프로세스만 본다. 여기는 계산만 두고 그리기와 $ 호출은 register.tsx 에.
8
9// 띠의 "지금" 줄은 턴이 이만큼 지나야 띄운다(질문 하나에 답하는 짧은 턴마다 줄이 생겼다 사라지지 않게).
10export const NOW_AFTER_MS = 10_000
11// 도구가 띄운 프로세스를 읽는 간격. 이보다 짧은 명령은 읽지 않는다.
12export const PROC_POLL_MS = 3000
13// 프로세스의 CPU·입출력이 이만큼 그대로면 "변화 없음"을 단다.
14export const QUIET_AFTER_MS = 180_000
15// /proc/<pid>/stat 의 utime·stime 단위(리눅스 CLK_TCK).
16const CLK_TCK = 100
17
18// etimes: 뜬 뒤 지난 초.
19export type ProcRow = { pid: number; ppid: number; etimes: number; name: string }
20
21// 프로세스 트리를 따라 내려가는 깊이(셸 래퍼 → 명령 → 그 자식 …).
22export const PROC_DEPTH = 6
23
24// Bash 도구는 명령을 늘 셸(bash -c …)로 감싸 띄운다. 같은 때 desk-look 이 띄운 git·gh 같은 자식은 이 이름이 아니다.
25const SHELLS = new Set(['bash', 'sh', 'zsh', 'dash', 'fish'])
26
27// claude 의 자식 가운데 이 호출의 셸 래퍼인가: 호출이 시작된 뒤 뜬 셸. 시각이 초 단위라 시작 직전에 뜬 래퍼도 받도록 1초를 더 준다.
28export const isCallRoot = (row: Pick<ProcRow, 'etimes' | 'name'>, sinceSec: number) => row.etimes <= sinceSec + 1 && SHELLS.has(row.name)
29
30// 도구 호출이 시작된 뒤 claude 아래에 생긴 셸 래퍼와 그 자손. MCP 서버처럼 먼저 떠 있던 자식과
31// desk-look 자신이 띄운 프로그램은 뺀다. leaves 는 자식이 없는 것(실제로 일하는 명령), 늦게 뜬 것이 앞.
32export function callProcesses(rows: ReadonlyArray<ProcRow>, claudePid: number, sinceSec: number): { pids: number[]; leaves: ProcRow[] } {
33  const children = new Map<number, ProcRow[]>()
34  for (const row of rows) children.set(row.ppid, [...(children.get(row.ppid) ?? []), row])
35  const roots = (children.get(claudePid) ?? []).filter(row => isCallRoot(row, sinceSec))
36  const pids: number[] = []
37  const leaves: ProcRow[] = []
38  const walk = (row: ProcRow) => {
39    pids.push(row.pid)
40    const kids = children.get(row.pid) ?? []
41    if (kids.length === 0) leaves.push(row)
42    kids.forEach(walk)
43  }
44  roots.forEach(walk)
45  leaves.sort((a, b) => a.etimes - b.etimes)
46  return { pids, leaves }
47}
48
49// /proc/<pid>/stat 의 utime+stime(틱). 이름(comm)은 괄호 안에 공백·괄호를 품을 수 있어 마지막 ')' 뒤부터 센다.
50export function statTicks(text: string): number | null {
51  const fields = text.slice(text.lastIndexOf(')') + 2).split(' ')
52  // ')' 뒤 첫 칸이 3번째 필드(state)라 utime(14)·stime(15)은 11·12번째.
53  const utime = Number(fields[11])
54  const stime = Number(fields[12])
55  return Number.isFinite(utime) && Number.isFinite(stime) && fields.length > 12 ? utime + stime : null
56}
57
58// /proc/<pid>/stat 한 줄에서 트리를 세우는 데 쓸 것: pid, 이름(comm), 부모, 시작 시각(부팅 뒤 틱), CPU 틱.
59export function statRow(text: string): { pid: number; name: string; ppid: number; startTicks: number; ticks: number } | null {
60  const open = text.indexOf('(')
61  const close = text.lastIndexOf(')')
62  if (open < 0 || close < open) return null
63  const fields = text.slice(close + 2).split(' ')
64  const pid = Number(text.slice(0, open).trim())
65  const ppid = Number(fields[1])
66  const startTicks = Number(fields[19])
67  const ticks = statTicks(text)
68  if (!Number.isInteger(pid) || !Number.isFinite(ppid) || !Number.isFinite(startTicks) || ticks === null) return null
69  return { pid, name: text.slice(open + 1, close), ppid, startTicks, ticks }
70}
71
72// /proc/uptime 의 첫 값(부팅 뒤 초)을 틱으로.
73export function uptimeTicks(text: string): number | null {
74  const seconds = Number(text.split(' ')[0])
75  return text.trim() !== '' && Number.isFinite(seconds) ? Math.round(seconds * CLK_TCK) : null
76}
77
78// /proc/<pid>/task/<pid>/children: 그 프로세스(메인 스레드)가 띄운 자식 pid 들.
79export const childPids = (text: string): number[] => text.split(/\s+/).filter(Boolean).map(Number).filter(Number.isInteger)
80
81// 틱 단위 시작 시각을 ps 의 etimes(초)로.
82export const etimesOf = (uptime: number, startTicks: number) => Math.floor((uptime - startTicks) / CLK_TCK)
83
84// /proc/self/stat 의 첫 필드: 이 훅이 도는 claude 의 pid.
85export function statPid(text: string): number | null {
86  const pid = Number(text.split(' ')[0])
87  return Number.isInteger(pid) && pid > 0 ? pid : null
88}
89
90// /proc/<pid>/io 의 rchar+wchar: 파이프·소켓까지 센 읽고 쓴 바이트.
91export function ioBytes(text: string): number | null {
92  const value = (key: string) => Number(new RegExp(`^${key}:\\s*(\\d+)`, 'm').exec(text)?.[1] ?? NaN)
93  const total = value('rchar') + value('wchar')
94  return Number.isFinite(total) ? total : null
95}
96
97export type ProcSample = { at: number; ticks: number; io: number }
98export type ProcView = { name: string; cpu: number | null; quietSince: number | null; isNetwork: boolean }
99
100// 원격이 일하는 동안 로컬은 조용한 명령: 오래 조용해도 경고 대신 흐린 사실만 단다.
101const NETWORK = new Set(['ssh', 'scp', 'sftp', 'rsync', 'mosh-client', 'curl', 'wget', 'gh', 'glab', 'git', 'kubectl', 'psql', 'mysql', 'redis-cli', 'nc', 'telnet'])
102
103// 직전 표본과 비교해 CPU%·조용해진 시각을 정한다. 첫 표본이면 아직 움직임을 모르니 CPU 는 null, 조용하지 않은 것으로.
104export function procView(name: string, prev: ProcSample | null, sample: ProcSample, prevView: ProcView | null): ProcView {
105  const isNetwork = NETWORK.has(name)
106  if (prev === null || sample.at <= prev.at) return { name, cpu: null, quietSince: null, isNetwork }
107  const ticks = Math.max(0, sample.ticks - prev.ticks)
108  const cpu = Math.round((ticks / CLK_TCK / ((sample.at - prev.at) / 1000)) * 100)
109  const isMoving = ticks > 0 || sample.io > prev.io
110  const quietSince = isMoving ? null : (prevView?.quietSince ?? prev.at)
111  return { name, cpu, quietSince, isNetwork }
112}
113
114export type StripPart = { kind: 'completed' | 'in_progress' | 'pending' | 'more'; text: string }
115
116// 할 일 목록을 한 줄 칸으로. 넘치면 끝난 일을 "✓ N" 하나로, 남은 일을 첫 하나와 "+N" 으로 접고,
117// 그래도 넘치면 하는 중인 일의 글을 줄인다. label 은 하는 중인 일의 글(진행형 문구·시간).
118export function stepStrip(list: ReadonlyArray<TaskItem>, columns: number, label: (item: TaskItem) => string): StripPart[] {
119  const mark = { completed: '✓', in_progress: '◉', pending: '○' } as const
120  const partOf = (item: TaskItem): StripPart => ({
121    kind: item.status,
122    text: `${mark[item.status]} ${item.status === 'in_progress' ? label(item) : item.subject}`,
123  })
124  const width = (parts: ReadonlyArray<StripPart>) => parts.reduce((sum, part) => sum + cellWidth(part.text) + 2, 0)
125  let parts = list.map(partOf)
126  if (width(parts) <= columns) return parts
127  const done = list.filter(item => item.status === 'completed').length
128  const open = list.filter(item => item.status !== 'completed')
129  const doneParts: StripPart[] = done > 0 ? [{ kind: 'completed', text: `✓ ${done}` }] : []
130  parts = [...doneParts, ...open.map(partOf)]
131  if (width(parts) <= columns) return parts
132  const active = open.filter(item => item.status === 'in_progress').map(partOf)
133  const pending = open.filter(item => item.status === 'pending')
134  const rest = pending.length - 1
135  parts = [...doneParts, ...active, ...pending.slice(0, 1).map(partOf), ...(rest > 0 ? [{ kind: 'more' as const, text: `+${rest}` }] : [])]
136  if (width(parts) <= columns) return parts
137  // 남은 폭에 맞춰 긴 글부터 자른다(하는 중인 일이 먼저, 그다음 다음 일).
138  const over = width(parts) - columns
139  return clipParts(parts, over)
140}
141
142// 할 일 도구가 없을 때(Claude 5 모델은 엔진이 꺼 둔다) 윗줄의 재료: 이번 턴에 모델이 도구를 부르며 쓴 설명 글.
143// 턴의 경계는 마지막 사람 프롬프트(도구 결과가 아닌 글 있는 user 메시지). 가장 늦은 설명의 첫 문장과 설명 수,
144// 그리고 그 설명 뒤에 부른 도구 호출 id(패널 흐름에서 설명을 그 호출들 앞에 두려고). 기록은 글 블록과
145// 도구 호출 블록을 따로 붙이므로 설명 메시지 자신과 그 뒤 assistant 메시지들의 호출을 모은다.
146export function turnNarration(messages: ReadonlyArray<SessionMessage>): { text: string; count: number; ids: string[] } | null {
147  let start = 0
148  messages.forEach((message, index) => {
149    if (message.role === 'user' && message.text.trim() !== '' && (message.toolResults ?? []).length === 0) start = index + 1
150  })
151  const turn = messages.slice(start)
152  const said = turn.filter(message => message.role === 'assistant' && message.text.trim() !== '')
153  const last = said[said.length - 1]
154  if (!last) return null
155  const ids = turn
156    .slice(turn.indexOf(last))
157    .filter(message => message.role === 'assistant')
158    .flatMap(message => message.toolUses.map(use => use.tool_use_id))
159  return { text: firstSentence(last.text), count: said.length, ids }
160}
161
162export function firstSentence(text: string): string {
163  const line =
164    text
165      .split('\n')
166      .map(row => row.replace(/^\s*(?:#+|>|[-*+]|\d+\.)\s+/, '').replace(/\*\*|__|`/g, '').trim())
167      .find(row => row !== '') ?? ''
168  return /^(.+?[.!?。])(?:\s|$)/.exec(line)?.[1] ?? line
169}
170
171// 설명 글 단계 칸: 앞선 설명은 "✓ N" 하나로, 지금 설명은 ◉ 로. 넘치면 지금 설명을 줄인다.
172export function sayStrip(text: string, done: number, columns: number): StripPart[] {
173  const parts: StripPart[] = [...(done > 0 ? [{ kind: 'completed' as const, text: `✓ ${done}` }] : []), { kind: 'in_progress', text: `◉ ${text}` }]
174  const over = parts.reduce((sum, part) => sum + cellWidth(part.text) + 2, 0) - columns
175  return over > 0 ? clipParts(parts, over) : parts
176}
177
178function clipParts(parts: StripPart[], over: number): StripPart[] {
179  let left = over
180  return parts.map(part => {
181    if (left <= 0 || (part.kind !== 'in_progress' && part.kind !== 'pending')) return part
182    const keep = Math.max(4, cellWidth(part.text) - left - 1)
183    const clipped = clipWidth(part.text, keep)
184    left -= cellWidth(part.text) - cellWidth(clipped)
185    return { ...part, text: clipped }
186  })
187}
188
189export function clipWidth(text: string, room: number): string {
190  if (cellWidth(text) <= room) return text
191  let out = ''
192  for (const ch of text) {
193    if (cellWidth(out + ch) > room - 1) break
194    out += ch
195  }
196  return `${out}…`
197}
198
199// ── /desk-activity 패널 ──
200
201export const LOG_EVENTS = 400
202
203const EXPLORE = new Set(['Read', 'Grep', 'Glob', 'LS', 'WebFetch', 'WebSearch', 'NotebookRead', 'ToolSearch', 'LSP'])
204const EDIT = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit'])
205// 테스트로 보는 명령: 흔한 테스트 실행기와 claude plugin test.
206const TEST = /(^|[\s;&|(])(bun test|npm (run )?test|pnpm (run )?test|yarn test|npx (jest|vitest)|jest|vitest|pytest|go test|cargo test|mvn\b.*\btest|gradle\w*\b.*\btest|tox|rspec|phpunit|claude plugin test|make test)\b/
207
208export function kindOf(tool: string, command?: string): ActivityKind {
209  if (EXPLORE.has(tool)) return 'explore'
210  if (EDIT.has(tool)) return 'edit'
211  if (tool === 'Agent' || tool === 'Task') return 'agent'
212  if (tool === 'Bash') return command !== undefined && TEST.test(command) ? 'test' : 'command'
213  return 'other'
214}
215
216// 막대에서 한 칸을 무엇으로 칠할지: 같은 칸에 여럿이 겹치면 짧은 사건(편집·테스트·탐색)이 이겨 긴 명령에 묻히지 않는다.
217const PRIORITY: ActivityKind[] = ['edit', 'test', 'explore', 'agent', 'command', 'other']
218// 오래 걸리는 일(명령·위임)은 굵은 선, 짧은 사건은 블록. 응답 중(idle)은 가는 선.
219export const KIND_GLYPH: Record<ActivityKind, string> = { explore: '░', edit: '▓', test: '▒', command: '━', agent: '━', other: '▪' }
220
221export type LaneSegment = { kind: ActivityKind | 'idle' | 'none'; text: string }
222
223// 한 줄 시간 막대: from~to 를 width 칸으로 나눠 칸마다 겹친 호출의 종류(없고 살아 있으면 idle, 아니면 none).
224// alive 는 그 줄의 주인이 살아 있던 구간(메인은 턴 전체, 에이전트는 시작~끝).
225export function laneSegments(events: ReadonlyArray<Pick<ActivityEvent, 'kind' | 'start' | 'end'>>, alive: { start: number; end: number }, from: number, to: number, width: number): LaneSegment[] {
226  const span = Math.max(1, to - from)
227  const cells: LaneSegment['kind'][] = []
228  for (let cell = 0; cell < width; cell++) {
229    const a = from + (span * cell) / width
230    const b = from + (span * (cell + 1)) / width
231    const hits = events.filter(event => event.start < b && (event.end ?? to) >= a).map(event => event.kind)
232    const best = PRIORITY.find(kind => hits.includes(kind))
233    cells.push(best ?? (alive.start < b && alive.end >= a ? 'idle' : 'none'))
234  }
235  const segments: LaneSegment[] = []
236  for (const kind of cells) {
237    const glyph = kind === 'idle' ? '─' : kind === 'none' ? ' ' : KIND_GLYPH[kind]
238    const last = segments[segments.length - 1]
239    if (last && last.kind === kind) last.text += glyph
240    else segments.push({ kind, text: glyph })
241  }
242  return segments
243}
244
245export type FlowRow =
246  | { at: number; kind: 'say'; text: string }
247  | { at: number; kind: 'explore'; text: string }
248  | { at: number; kind: 'edit'; text: string; added: number; removed: number; isError: boolean }
249  | { at: number; kind: 'command' | 'test' | 'agent' | 'other'; text: string; ms: number | null; isError: boolean }
250
251// 패널의 흐름: 메인 대화의 설명 글과 호출을 시간 순으로. 이어진 탐색은 "Read 6 · Grep 3" 한 줄로,
252// 같은 파일을 잇달아 고친 것은 한 줄로 합친다. 도는 중인 호출은 ms 가 null.
253export function flowRows(log: ActivityLog): FlowRow[] {
254  const items = [
255    ...log.says.map(say => ({ at: say.at, say })),
256    ...log.events.filter(event => event.loop === undefined).map(event => ({ at: event.start, event })),
257  ].sort((a, b) => a.at - b.at || ('say' in a ? -1 : 0) - ('say' in b ? -1 : 0))
258  const rows: FlowRow[] = []
259  let tally: Map<string, number> | null = null
260  for (const item of items) {
261    if ('say' in item) {
262      tally = null
263      rows.push({ at: item.at, kind: 'say', text: item.say.text })
264      continue
265    }
266    const event = item.event
267    const last = rows[rows.length - 1]
268    if (event.kind === 'explore') {
269      if (!tally || last?.kind !== 'explore') {
270        tally = new Map()
271        rows.push({ at: event.start, kind: 'explore', text: '' })
272      }
273      tally.set(event.tool, (tally.get(event.tool) ?? 0) + 1)
274      const row = rows[rows.length - 1] as Extract<FlowRow, { kind: 'explore' }>
275      row.text = [...tally].map(([tool, count]) => (count > 1 ? `${tool} ${count}` : tool)).join(' · ')
276      continue
277    }
278    tally = null
279    if (event.kind === 'edit') {
280      if (last?.kind === 'edit' && last.text === event.label) {
281        last.added += event.added ?? 0
282        last.removed += event.removed ?? 0
283        last.isError = last.isError && event.isError === true
284        continue
285      }
286      rows.push({ at: event.start, kind: 'edit', text: event.label, added: event.added ?? 0, removed: event.removed ?? 0, isError: event.isError === true })
287      continue
288    }
289    rows.push({ at: event.start, kind: event.kind, text: event.label, ms: event.end === undefined ? null : event.end - event.start, isError: event.isError === true })
290  }
291  return rows
292}
293
294// 턴 시작부터의 시각: 12:05 처럼 분:초(한 시간을 넘으면 1:02:05).
295export function clockOf(ms: number): string {
296  const total = Math.max(0, Math.floor(ms / 1000))
297  const pad = (value: number) => String(value).padStart(2, '0')
298  const hours = Math.floor(total / 3600)
299  const rest = `${pad(Math.floor((total % 3600) / 60))}:${pad(total % 60)}`
300  return hours > 0 ? `${hours}:${rest}` : rest
301}
302