SLOPSHOPPER

work-report

Counts the tasks Claude finishes for you and estimates the hours saved and what that time is worth, by day, week, month and year.

panespinnerguardcommandtoastprompt
v0.4.1no licenseupdated 2026-10-22iansutherland75/claude-mods/mods/work-report
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · work-report
│ ┃ Work Report ✕ › fix the failing auth test and add an audit log call │ ┃ tab-today tab-week tab-month tab-year │ ┃ ⏺ Read(src/auth.ts) │ ┃ TODAY ⎿ Read 6 lines │ ┃ ━━━━━─────────────────────────────────────── ⏺ Update(src/auth.ts) │ ┃ ⎿ Added 2 lines, removed 1 line │ ┃ ╭─────────────────────────╮ ╭─────────────── ⏺ Bash(bun test) │ ┃ │ ┏━┓ ┏━╸ │ │ ╺┓ ⎿ 3 pass, 1 fail │ ┃ │ ┃ ┃ ┣━┓ │ │ ┃ │ ┃ │ ┗━┛ ▪ ┗━┛ │ │ ╺┻╸ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ EST. HOURS SAVED │ │ TASKS DONE │ ┃ ╰─────────────────────────╯ ╰─────────────── ✻ Worked for 42s · done 4:20 PM │ ┃ ╭─────────────────────────╮ │ ┃ │ ┏╋╸ ╺━┓ ╺━┓ │ › /report │ ┃ │ ┗╋┓ ━┫ ┏━┛ │ ⎿ work-report: Work Report is open. Hours and dollars are estimate │ ┃ │ ╺╋┛ ╺━┛ ┗━╸ │ │ ┃ │ EST. VALUE │ │ ┃ ╰─────────────────────────╯ │ ┃ Estimates: minutes saved per task, building │ ┃ 25 lines of code an hour, at $50 an hour. │ ┃ │ ┃ WHERE THE TIME WENT · EST. HOURS ─────────── │ ┃ Emails ─────────────────────────── │ ┃ Documents ─────────────────────────── │ ┃ Building softwa… ━━━━━━━━━━━━━━━━━━━━━━━━━━━ │ ┃ Images and video ─────────────────────────── ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⟨Claude Code's own drawing⟩ open-work-report

Draws

Pane · Work Report
tab-today tab-week tab-month tab-year TODAY Thu, Oct 9 ━━━━━─────────────────────────────────────────────────── ╭─────────────────────────╮ ╭─────────────────────────╮ │ ┏━┓ ┏━╸ │ │ ╺┓ │ │ ┃ ┃ ┣━┓ │ │ ┃ │ │ ┗━┛ ▪ ┗━┛ │ │ ╺┻╸ │ │ EST. HOURS SAVED │ │ TASKS DONE │ ╰─────────────────────────╯ ╰─────────────────────────╯ ╭─────────────────────────╮ │ ┏╋╸ ╺━┓ ╺━┓ │ │ ┗╋┓ ━┫ ┏━┛ │ │ ╺╋┛ ╺━┛ ┗━╸ │ │ EST. VALUE │ ╰─────────────────────────╯ Estimates: minutes saved per task, building software at 25 lines of code an hour, at $50 an hour. WHERE THE TIME WENT · EST. HOURS ─────────────────────── Emails ─────────────────────────────── 0 0h Documents ─────────────────────────────── 0 0h Building softwa… ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1 0.6h Images and video ─────────────────────────────── 0 0h Research ─────────────────────────────── 0 0h Other ─────────────────────────────── 0 0h BY PROJECT · EST. HOURS ──────────────────────────────── src ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1 0.6h WHO DID THE WORK ─────────────────────────────────────── Opus 5.5 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1 THE LAST 7 DAYS ──────────────────────────────────────── ███████ ███████ ▁▁▁▁▁▁▁ ▁▁▁▁▁▁▁ ▁▁▁▁▁▁▁ ▁▁▁▁▁▁▁ ▁▁▁▁▁▁▁ ▁▁▁▁▁▁▁ ███████ Fr Sa Su Mo Tu We Th Streak: 1 day. close
README

claude-mods

Ian's Claude Code mods. The repo is a plugin marketplace called ian-mods, and each mod lives in its own folder under mods/.

ModWhat it does
prompt-upgrade/better <prompt> asks up to three quick questions, rewrites the prompt and shows the original and the rewrite side by side. Nothing runs until you press Run. /better on sends what you type to it first.
work-report/report opens a pane with the tasks Claude finished for you and an estimate of the hours saved and what that time is worth, for today, the last 7 days, the last 30 days and the year. /report settings shows and changes the minutes per task and the hourly rate. /report backfill fills in past days from this machine's session history (needs Python 3: /usr/bin/python3 on a Mac, py or python on Windows). Building software is estimated from the lines of code written (/report settings buildrate 25), and a By project section shows hours per repo. /report add "QBR builder" 160 2026-05-01 adds hours for older work (/report list, /report remove 1). Counts are kept per machine.
skill-routerRuns each skill and subagent on the right size of model, and has Fable check the finished work. Simple fixed-step skills (docket, schedule, loop, keybindings-help, consolidate-memory) always run on Haiku. For the rest, Jev (TypeSafe's decision model on OpenRouter) picks Haiku, Sonnet or Opus, never above the session model, and the session model comes back on your next prompt. Every subagent gets the same treatment: the session picks the agent's role, Jev picks its size. Each session starts with conductor rules: when to hand work to subagents and when to do it inline. When a turn changed files (Edit, Write, NotebookEdit or an Artifact publish), a Stop hook keeps it going until the final-review agent has checked the work on Fable and answered PASS or FIX. It asks once per prompt: edits made after that review end without a second one (logged as review skipped). Files written by Bash don't trigger it. While subagents run, a band above the chat box shows one row per agent: a dot and chip in the model colour (Haiku green, Sonnet blue, Opus purple, Fable gold), the agent and its task, a thin progress bar, and what it is doing. The bar fills by tool calls against the usual count for that agent type and holds at 90% until the agent finishes. Finished rows clear on your next typed message, and the band goes with them. The band's [-] collapses it. /skill-router pane opens the full cards beside the chat, which also show how the model was chosen (what Jev was offered, its pick, how sure it was and how long it took). /skill-router view band, view pane or view off picks where agents show by themselves. Each pick and review is logged with its time, cost and tokens. /skill-router log, /skill-router off/on (skills), /skill-router agents off/on, /skill-router review off/on. Needs an OpenRouter key in the OPENROUTER_API_KEY environment variable or in the login Keychain (see below).

Set up a machine

The clone lives at ~/claude-mods on every machine. Install each mod once per machine at user scope. After that it loads in every local session: the desktop app's Code tab and the terminal.

git clone https://github.com/iansutherland75/claude-mods.git ~/claude-mods
claude plugin marketplace add ~/claude-mods
claude plugin install prompt-upgrade@ian-mods --scope user
claude plugin install work-report@ian-mods --scope user
claude plugin install skill-router@ian-mods --scope user

skill-router reads its OpenRouter key from the login Keychain. Copy the key, then run this once per machine. It never shows the key:

security add-generic-password -U -a "$USER" -s OPENROUTER_API_KEY -w "$(pbpaste)"

Run these with Claude Code 2.1.295 or newer. If claude --version shows an older build, run brew upgrade claude-code first.

Keep machines in step

The marketplace is a local folder, so sessions read each mod straight from ~/claude-mods. Nothing needs reinstalling after a change.

  1. git pull in ~/claude-mods.
  2. Run /reload-plugins in any open session. New sessions pick it up on their own.

A new mod needs one extra step on each machine: claude plugin install <mod>@ian-mods --scope user.

Add a mod

  1. Put it in mods/<mod-name>/ with its .claude-plugin/plugin.json, hooks/ and tests.
  2. Add an entry to .claude-plugin/marketplace.json with "source": "./mods/<mod-name>".
  3. Check it: claude plugin validate mods/<mod-name> and claude plugin test mods/<mod-name>.
  4. Commit, push, then install it on each machine.

Not covered

Cloud sessions (claude.ai/code, cloud Cowork) do not see mods installed on a machine.

Source 4 files
hooks/register.tsx 834 lines
1import type { Elements, EngineInterface, Register } from 'claude-code'
2
3import type { DayRecord, Kind, ManualEntry, Settings, Tab } from '../types'
4import {
5  DEFAULT_SETTINGS,
6  KINDS,
7  KIND_LABEL,
8  addDays,
9  addTask,
10  applySetting,
11  barCells,
12  barsOf,
13  bigText,
14  clip,
15  dayKey,
16  daysOf,
17  emptyText,
18  hoursText,
19  isTypedPrompt,
20  kindMinutes,
21  kindOf,
22  manualListText,
23  minutesSaved,
24  parseAdd,
25  projectOfTask,
26  projectRows,
27  readManual,
28  taskLines,
29  writtenLines,
30  modelName,
31  moneyText,
32  pathsOf,
33  historyDays,
34  readDay,
35  readHistory,
36  readSettings,
37  shortDate,
38  streak,
39  sumDays,
40  summaryOf,
41  tasksOn,
42  tilesPerRow,
43  titleOf,
44  wrap,
45} from './logic'
46import type { Bar, ToolUse, Totals } from './logic'
47import { barRowsSvg, chartSvg, headerSvg, kindRows, pixelsFor, projectBarRows, tilesSvg } from './desktop'
48import type { Drawing } from './desktop'
49
50type D = EngineInterface
51
52const PANE = 'work-report'
53const TITLE = 'Work Report'
54const TABS: readonly Tab[] = ['today', 'week', 'month', 'year']
55const TAB_LABEL: Record<Tab, string> = { today: 'Today', week: 'Week', month: 'Month', year: 'Year' }
56
57const GOLD = '#F2C46D'
58const LINE = '#262B33'
59const MUTED = '#7D8590'
60const TEXT = '#E6EDF3'
61const GREEN = '#3DD68C'
62const INK = '#0D1117'
63
64const KIND_COLOR: Record<Kind, string> = {
65  emails: '#79C0FF',
66  documents: GOLD,
67  building: '#F0876A',
68  media: '#D2A8FF',
69  research: '#56D4DD',
70  other: MUTED,
71}
72const MODEL_COLORS = [GOLD, '#79C0FF', '#D2A8FF', '#56D4DD', GREEN, MUTED]
73
74const FAILED = 'Work Report hit a problem and could not do that. Nothing was changed.'
75const NARROW = 'Work Report needs a wider window. Widen it and run /report again.'
76
77// ---------------------------------------------------------------- state
78
79const DAYS = { plugin: 'work-report', key: 'days' } as const
80const SETTINGS = { plugin: 'work-report', key: 'settings' } as const
81const TAB = { plugin: 'work-report', key: 'tab' } as const
82const MANUAL = { plugin: 'work-report', key: 'manual' } as const
83
84// Reads while drawing subscribe the drawing; writes come only from events.
85const getDays = async ($: D): Promise<Record<string, DayRecord>> => (await $.state.get(DAYS)).value ?? {}
86const getSettings = async ($: D): Promise<Settings> => readSettings((await $.state.get(SETTINGS)).value)
87const getTab = async ($: D): Promise<Tab> => (await $.state.get(TAB)).value ?? 'today'
88const getManual = async ($: D): Promise<ManualEntry[]> => readManual((await $.state.get(MANUAL)).value)
89
90// Hours added by hand: kept in the store, mirrored into state for drawing.
91const loadManual = async ($: D) => {
92  await $.state.set(MANUAL, readManual(await $.store.get('manual')))
93}
94
95const saveManual = async ($: D, list: ManualEntry[]) => {
96  await $.store.set('manual', list)
97  await $.state.set(MANUAL, list)
98}
99
100const todayOf = async ($: D) => dayKey(new Date(await $.clock.now()))
101
102// Read, apply, write with ifVersion; again on a miss.
103const changeDays = async ($: D, change: (days: Record<string, DayRecord>) => Record<string, DayRecord>) => {
104  for (let tries = 0; tries < 20; tries++) {
105    const now = await $.state.get(DAYS)
106    const result = await $.state.set(DAYS, change(now.value ?? {}), { ifVersion: now.version })
107    if (result.isSet) return
108  }
109}
110
111// Loads the kept days the tabs can show (this calendar year and the last 31
112// days) so every session on this machine sees the same counts.
113const loadDays = async ($: D) => {
114  const today = await todayOf($)
115  const oldest = [`${today.slice(0, 4)}-01-01`, addDays(today, -31)].sort()[0]!
116  const loaded: Record<string, DayRecord> = {}
117  for (const name of await $.store.keys()) {
118    if (!name.startsWith('day:')) continue
119    const key = name.slice(4)
120    if (key < oldest) continue
121    const day = readDay(await $.store.get(name))
122    if (day !== undefined) loaded[key] = day
123  }
124  await changeDays($, () => loaded)
125}
126
127const loadSettings = async ($: D) => {
128  await $.state.set(SETTINGS, readSettings(await $.store.get('settings')))
129}
130
131const record = async ($: D, kind: Kind, model: string, project: string, lines: number) => {
132  const today = await todayOf($)
133  const day = addTask(readDay(await $.store.get(`day:${today}`)), kind, model, project, lines)
134  await $.store.set(`day:${today}`, day)
135  await changeDays($, days => ({ ...days, [today]: day }))
136}
137
138const openReport = async ($: D) => {
139  await loadDays($)
140  const opened = await $.ui.open({ id: PANE, title: TITLE })
141  if (!opened.isPlaced) $.ui.toast(NARROW)
142}
143
144const BACKFILL_FAILED = 'Work Report could not read your session history. Nothing was changed.'
145
146// Windows keeps the home folder in USERPROFILE; HOME is the Mac and Linux one.
147const homeFolder = async ($: D) => (await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME'))
148
149// Python by the names each system gives it. A name that is not installed
150// rejects; the Windows Store stub exits 9009. Either way, try the next.
151const pythons = (home: string | undefined): readonly (readonly string[])[] =>
152  home !== undefined && /^[A-Za-z]:/.test(home)
153    ? [['py', '-3'], ['python'], ['python3']]
154    : [['/usr/bin/python3'], ['python3'], ['python']]
155const NO_INTERPRETER = new Set([9009, 126, 127])
156
157// Fills in past days from this machine's session transcripts. Read-only on the
158// transcripts; each day it finds replaces that day's record, so running it
159// again never counts a request twice.
160const backfill = async ($: D) => {
161  const home = await homeFolder($)
162  const folder = home !== undefined && home.includes('\\') ? '\\' : '/'
163  const config = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? (home === undefined ? undefined : `${home}${folder}.claude`)
164  if (config === undefined) {
165    $.ui.toast(BACKFILL_FAILED)
166
167    return
168  }
169  const script = `${$.plugin.root}/scripts/history.py`
170  const projects = `${config}${config.includes('\\') ? '\\' : '/'}projects`
171  let run: Awaited<ReturnType<D['process']['run']>> | undefined
172  for (const python of pythons(home)) {
173    try {
174      const tried = await $.process.run([...python, '-I', script, projects], { timeoutMs: 600_000 })
175      if (NO_INTERPRETER.has(tried.exitCode)) continue
176      run = tried
177      break
178    } catch {
179      // this name is not installed
180    }
181  }
182  if (run === undefined || run.exitCode !== 0 || run.isStdoutTruncated) {
183    $.ui.toast(BACKFILL_FAILED)
184
185    return
186  }
187  const tasks = readHistory(run.stdout)
188  const days = historyDays(tasks, home ?? '')
189  for (const [key, day] of Object.entries(days)) await $.store.set(`day:${key}`, day)
190  await loadDays($)
191  const keys = Object.keys(days).sort()
192  const first = keys[0]
193  const last = keys[keys.length - 1]
194  $.ui.toast(
195    first === undefined || last === undefined
196      ? 'Work Report found no finished requests in your session history.'
197      : `Work Report filled in ${tasks.length} tasks from your session history, ${shortDate(first)} to ${shortDate(last)}.`,
198  )
199}
200
201const act = (work: () => Promise<unknown>) => () => {
202  void work().catch(() => undefined)
203}
204
205// ---------------------------------------------------------------- drawing
206
207type Kit = {
208  Box: Elements['terminal']['Box']
209  Text: Elements['terminal']['Text']
210  Button: Elements['terminal']['Button']
211}
212
213type Chip = { key: string; label: string; tone: 'gold' | 'slate' | 'quiet'; onPress: () => void }
214
215const chipWidth = (chip: Chip) => (chip.tone === 'quiet' ? chip.label.length : chip.label.length + 2)
216
217const drawChip = (kit: Kit, chip: Chip) => {
218  const { Button, Text } = kit
219  if (chip.tone === 'quiet') {
220    return (
221      <Button key={chip.key} plain onPress={chip.onPress}>
222        <Text color={MUTED}>{chip.label}</Text>
223      </Button>
224    )
225  }
226
227  return (
228    <Button key={chip.key} plain onPress={chip.onPress}>
229      <Text backgroundColor={chip.tone === 'gold' ? GOLD : LINE} color={chip.tone === 'gold' ? INK : TEXT} bold={chip.tone === 'gold'}>
230        {` ${chip.label} `}
231      </Text>
232    </Button>
233  )
234}
235
236// Chips laid out in rows that each fit the width.
237const drawChips = (kit: Kit, chips: Chip[], width: number) => {
238  const { Box } = kit
239  const rows: Chip[][] = []
240  let row: Chip[] = []
241  let used = 0
242  for (const chip of chips.map(one => ({ ...one, label: clip(one.label, Math.max(1, width - 2)) }))) {
243    const w = chipWidth(chip)
244    if (row.length > 0 && used + 1 + w > width) {
245      rows.push(row)
246      row = []
247      used = 0
248    }
249    used += (row.length > 0 ? 1 : 0) + w
250    row.push(chip)
251  }
252  if (row.length > 0) rows.push(row)
253
254  return (
255    <Box flexDirection="column" width={width}>
256      {rows.map(line => (
257        <Box flexDirection="row" gap={1}>
258          {line.map(chip => drawChip(kit, chip))}
259        </Box>
260      ))}
261    </Box>
262  )
263}
264
265const drawTabs = ($: D, kit: Kit, width: number, tab: Tab) =>
266  drawChips(
267    kit,
268    TABS.map(one => ({
269      key: `tab-${one}`,
270      label: TAB_LABEL[one],
271      tone: one === tab ? 'gold' : 'slate',
272      onPress: act(async () => {
273        await loadDays($)
274        await $.state.set(TAB, one)
275      }),
276    })),
277    width,
278  )
279
280const drawTitle = (kit: Kit, width: number, name: string, dates: string) => {
281  const { Box, Text } = kit
282  const title = clip(name, width)
283  const hasDates = title.length + 2 + dates.length <= width
284  const gold = Math.min(title.length, width)
285
286  return (
287    <Box flexDirection="column" width={width} marginTop={1}>
288      <Box flexDirection="row" justifyContent="space-between" width={width}>
289        <Text bold color={TEXT}>
290          {title}
291        </Text>
292        {hasDates && <Text color={MUTED}>{dates}</Text>}
293      </Box>
294      <Box flexDirection="row" width={width}>
295        <Text color={GOLD}>{'━'.repeat(gold)}</Text>
296        <Text color={LINE}>{'─'.repeat(Math.max(0, width - gold))}</Text>
297      </Box>
298    </Box>
299  )
300}
301
302const drawSection = (kit: Kit, width: number, label: string) => {
303  const { Box, Text } = kit
304  const shown = clip(label.toUpperCase(), width)
305
306  return (
307    <Box flexDirection="row" width={width} marginTop={1}>
308      <Text color={MUTED}>{shown}</Text>
309      <Text color={LINE}>{shown.length + 1 < width ? ` ${'─'.repeat(width - shown.length - 1)}` : ''}</Text>
310    </Box>
311  )
312}
313
314const TILE_MIN = 20
315
316const drawTiles = (kit: Kit, width: number, totals: Totals, settings: Settings) => {
317  const { Box, Text } = kit
318  const minutes = minutesSaved(totals, settings)
319  const tiles = [
320    { key: 'hours', value: hoursText(minutes), plain: `${hoursText(minutes)} h`, label: 'EST. HOURS SAVED', color: GOLD },
321    { key: 'tasks', value: String(totals.tasks), plain: totals.tasks.toLocaleString('en-US'), label: 'TASKS DONE', color: TEXT },
322    {
323      key: 'value',
324      value: moneyText(minutes, settings.rate),
325      plain: moneyText(minutes, settings.rate, true),
326      label: 'EST. VALUE',
327      color: GREEN,
328    },
329  ]
330  const perRow = tilesPerRow(width, TILE_MIN, tiles.length)
331  const tileWidth = Math.floor((width - (perRow - 1)) / perRow)
332  const inner = Math.max(1, tileWidth - 4)
333  const rows: (typeof tiles)[] = []
334  for (let i = 0; i < tiles.length; i += perRow) rows.push(tiles.slice(i, i + perRow))
335
336  return (
337    <Box flexDirection="column" width={width} marginTop={1}>
338      {rows.map(row => (
339        <Box flexDirection="row" gap={1} width={width}>
340          {row.map(tile => {
341            const glyph = bigText(tile.value)
342            const isBig = glyph[0].length <= inner
343
344            return (
345              <Box key={`tile-${tile.key}`} borderStyle="round" borderColor={LINE} paddingX={1} flexDirection="column" width={tileWidth}>
346                {isBig
347                  ? glyph.map(line => (
348                      <Text color={tile.color} bold>
349                        {line}
350                      </Text>
351                    ))
352                  : [' ', clip(tile.plain, inner), ' '].map(line => (
353                      <Text color={tile.color} bold>
354                        {line}
355                      </Text>
356                    ))}
357                <Text color={MUTED}>{clip(tile.label, inner)}</Text>
358              </Box>
359            )
360          })}
361        </Box>
362      ))}
363    </Box>
364  )
365}
366
367// A labelled bar row: the label, a colored bar on a dim track, then the figures.
368const drawBarRow = (kit: Kit, width: number, row: { key: string; label: string; value: number; max: number; color: string; figures: string }) => {
369  const { Box, Text } = kit
370  const labelWidth = Math.min(16, Math.max(6, Math.floor(width * 0.35)))
371  const figures = row.figures
372  const track = width - labelWidth - 1 - 1 - figures.length
373  const isZero = row.value === 0
374
375  if (track < 3) {
376    const label = clip(row.label, Math.max(1, width - figures.length - 1))
377
378    return (
379      <Box key={row.key} flexDirection="row" width={width}>
380        <Text color={isZero ? MUTED : TEXT}>{label.padEnd(width - figures.length)}</Text>
381        <Text color={isZero ? MUTED : TEXT}>{figures}</Text>
382      </Box>
383    )
384  }
385  const filled = row.max <= 0 || isZero ? 0 : Math.max(1, Math.round((row.value / row.max) * track))
386
387  return (
388    <Box key={row.key} flexDirection="row" width={width}>
389      <Text color={isZero ? MUTED : TEXT}>{`${clip(row.label, labelWidth).padEnd(labelWidth)} `}</Text>
390      <Text color={row.color}>{'━'.repeat(filled)}</Text>
391      <Text color={LINE}>{`${'─'.repeat(track - filled)} `}</Text>
392      <Text color={isZero ? MUTED : TEXT}>{figures}</Text>
393    </Box>
394  )
395}
396
397const drawKinds = (kit: Kit, width: number, totals: Totals, settings: Settings) => {
398  const { Box } = kit
399  const max = Math.max(...KINDS.map(kind => kindMinutes(totals, kind, settings)))
400  const hourTexts = KINDS.map(kind => `${hoursText(kindMinutes(totals, kind, settings))}h`)
401  const hourWidth = Math.max(...hourTexts.map(text => text.length))
402  const countWidth = Math.max(...KINDS.map(kind => String(totals.kinds[kind]).length))
403
404  return (
405    <Box flexDirection="column" width={width}>
406      {drawSection(kit, width, 'Where the time went · est. hours')}
407      {KINDS.map((kind, i) =>
408        drawBarRow(kit, width, {
409          key: `kind-${kind}`,
410          label: KIND_LABEL[kind],
411          value: kindMinutes(totals, kind, settings),
412          max,
413          color: KIND_COLOR[kind],
414          figures: `${String(totals.kinds[kind]).padStart(countWidth)}  ${hourTexts[i]!.padStart(hourWidth)}`,
415        }),
416      )}
417    </Box>
418  )
419}
420
421const drawModels = (kit: Kit, width: number, totals: Totals) => {
422  const { Box } = kit
423  const list = Object.entries(totals.models)
424    .sort((a, b) => b[1] - a[1])
425    .slice(0, 6)
426  const max = list[0]?.[1] ?? 0
427  const countWidth = Math.max(1, ...list.map(([, n]) => String(n).length))
428
429  return (
430    <Box flexDirection="column" width={width}>
431      {drawSection(kit, width, 'Who did the work')}
432      {list.map(([model, n], i) =>
433        drawBarRow(kit, width, {
434          key: `model-${i}`,
435          label: model,
436          value: n,
437          max,
438          color: MODEL_COLORS[i % MODEL_COLORS.length]!,
439          figures: String(n).padStart(countWidth),
440        }),
441      )}
442    </Box>
443  )
444}
445
446const drawProjects = (kit: Kit, width: number, totals: Totals, settings: Settings) => {
447  const { Box } = kit
448  const rows = projectRows(totals, settings)
449  if (rows.length === 0) return null
450  const max = Math.max(...rows.map(row => row.minutes))
451  const hourTexts = rows.map(row => `${hoursText(row.minutes)}h`)
452  const hourWidth = Math.max(...hourTexts.map(text => text.length))
453  const countWidth = Math.max(...rows.map(row => String(row.tasks).length))
454
455  return (
456    <Box flexDirection="column" width={width}>
457      {drawSection(kit, width, 'By project · est. hours')}
458      {rows.map((row, i) =>
459        drawBarRow(kit, width, {
460          key: `project-${i}`,
461          label: row.name,
462          value: row.minutes,
463          max,
464          color: MODEL_COLORS[i % MODEL_COLORS.length]!,
465          figures: `${String(row.tasks).padStart(countWidth)}  ${hourTexts[i]!.padStart(hourWidth)}`,
466        }),
467      )}
468    </Box>
469  )
470}
471
472const CHART_HEADING: Record<Tab, string> = {
473  today: 'The last 7 days',
474  week: 'The last 7 days',
475  month: 'The last 30 days',
476  year: 'Month by month',
477}
478
479const barColor = (bar: Bar) => (bar.isCurrent ? GOLD : bar.isFuture ? LINE : MUTED)
480
481const drawChart = (kit: Kit, width: number, tab: Tab, all: Bar[], today: string) => {
482  const { Box, Text } = kit
483  // Too narrow for thirty: the most recent days that fit.
484  const bars = all.length > width ? all.slice(all.length - width) : all
485  const slot = Math.max(1, Math.floor(width / bars.length))
486  const barWidth = slot >= 3 ? slot - 1 : 1
487  const gap = slot - barWidth
488  const max = Math.max(0, ...bars.map(bar => bar.value))
489
490  const rows = [0, 1, 2].map(row => (
491    <Box flexDirection="row" width={width}>
492      {bars.map(bar => {
493        const cells = barCells(bar.value, max)
494        const isBase = row === 2 && bar.value === 0 && !bar.isFuture
495
496        return (
497          <Text color={isBase ? LINE : barColor(bar)}>{`${(isBase ? '▁' : cells[row]!).repeat(barWidth)}${' '.repeat(gap)}`}</Text>
498        )
499      })}
500    </Box>
501  ))
502
503  let labels
504  if (tab === 'month') {
505    const first = shortDate(addDays(today, -(bars.length - 1)))
506    const last = 'Today'
507    const room = bars.length * slot
508    labels =
509      room >= first.length + last.length + 1 ? (
510        <Box flexDirection="row" width={width}>
511          <Text color={MUTED}>{first.padEnd(room - last.length)}</Text>
512          <Text color={GOLD}>{last}</Text>
513        </Box>
514      ) : (
515        <Text color={MUTED}>{clip(first, width)}</Text>
516      )
517  } else {
518    labels = (
519      <Box flexDirection="row" width={width}>
520        {bars.map(bar => (
521          <Text color={bar.isCurrent ? GOLD : MUTED}>{(slot >= 2 ? bar.label : bar.label.charAt(0)).slice(0, slot).padEnd(slot)}</Text>
522        ))}
523      </Box>
524    )
525  }
526
527  return (
528    <Box flexDirection="column" width={width}>
529      {drawSection(kit, width, CHART_HEADING[tab])}
530      {rows}
531      {labels}
532    </Box>
533  )
534}
535
536// ---------------------------------------------------------------- hooks
537
538export const register: Register = on => {
539  // Typed prompts waiting for their turn, and the turn being counted.
540  let pending: { text: string; turnId?: string }[] = []
541  let current: { turnId: string; uses: ToolUse[]; cwd: string } | null = null
542  let lastCommandAt = -Infinity
543  let home = ''
544
545  on('session.start', async ($, e, next) => {
546    try {
547      await $.command.register({
548        name: 'report',
549        description: 'Open the Work Report: tasks Claude finished and the time it saved. Also: week, month, year, settings, backfill, add, list, remove',
550        argumentHint: '[today | week | month | year | settings | backfill | add | list | remove]',
551      })
552    } catch {
553      // registration refused; counting still works
554    }
555    try {
556      home = (await homeFolder($).catch(() => undefined)) ?? ''
557      await loadSettings($)
558      await loadManual($)
559      await loadDays($)
560    } catch {
561      // nothing kept yet
562    }
563
564    return next(e)
565  })
566
567  on('command.run', { command: 'report' }, async ($, e) => {
568    try {
569      const words = e.args.trim().split(/\s+/).filter(Boolean)
570      const first = (words[0] ?? '').toLowerCase()
571
572      if (first === 'settings') {
573        const result = applySetting(words.slice(1).join(' '), await getSettings($))
574        if (result.settings !== undefined) {
575          await $.state.set(SETTINGS, result.settings)
576          await $.store.set('settings', result.settings)
577        }
578
579        return { text: result.text }
580      }
581
582      if (first === 'add') {
583        const parsed = parseAdd(e.args.trim().slice(3), await todayOf($))
584        if (parsed.entry === undefined) return { text: parsed.text ?? FAILED }
585        const list = await getManual($)
586        const entry: ManualEntry = { ...parsed.entry, id: `${await $.clock.now()}-${list.length}` }
587        await saveManual($, [...list, entry])
588
589        return { text: `Added ${entry.hours} estimated hours for ${entry.project} on ${entry.date}. /report list shows everything you have added.` }
590      }
591
592      if (first === 'list') return { text: manualListText(await getManual($)) }
593
594      if (first === 'remove') {
595        const list = await getManual($)
596        const n = Number(words[1])
597        if (!Number.isInteger(n) || n < 1 || n > list.length) {
598          return { text: list.length === 0 ? manualListText(list) : `Give the number from /report list, from 1 to ${list.length}, like /report remove 1.` }
599        }
600        const gone = list[n - 1]!
601        await saveManual($, list.filter((_, i) => i !== n - 1))
602
603        return { text: `Removed ${gone.hours} hours for ${gone.project} on ${gone.date}.` }
604      }
605
606      if (first === 'backfill') {
607        $.clock.after(0, () => {
608          void backfill($).catch(() => $.ui.toast(BACKFILL_FAILED))
609        })
610
611        return {
612          text: 'Reading your session history on this machine. The report fills in when it is done. Nothing leaves this computer.',
613        }
614      }
615
616      const tab = TABS.find(one => one === first)
617      if (first !== '' && tab === undefined) {
618        return { text: 'Try /report, /report week, /report month, /report year, /report settings, /report add, /report list or /report backfill.' }
619      }
620      if (tab !== undefined) await $.state.set(TAB, tab)
621      void openReport($).catch(() => undefined)
622
623      return { text: 'Work Report is open. Hours and dollars are estimates.' }
624    } catch {
625      return { text: FAILED }
626    }
627  }).catch(() => ({ text: FAILED }))
628
629  // A slash command that expands into a prompt is not a typed request.
630  on('command.run', async ($, e, next) => {
631    lastCommandAt = await $.clock.now()
632
633    return next(e)
634  }).catch(($, e, next) => next(e))
635
636  on('prompt.submit', async ($, e, next) => {
637    const isCommand = (await $.clock.now()) - lastCommandAt < 1500
638    const origin = e.origin
639    const isTyped =
640      !isCommand &&
641      isTypedPrompt({
642        originKind: origin.kind,
643        asUser: origin.kind === 'plugin' ? origin.asUser : undefined,
644        text: e.text,
645        hasAttachments: (e.attachments?.length ?? 0) > 0,
646      })
647    const entry = { text: e.text, turnId: e.turnId }
648    if (isTyped) pending = [...pending, entry].slice(-20)
649
650    const result = await next(e)
651    if (result.drop !== undefined) pending = pending.filter(one => one !== entry)
652
653    return result
654  }).catch(($, e, next) => next(e))
655
656  on('turn.start', async ($, e, next) => {
657    // The prompt the turn starts with, else the oldest typed while idle.
658    const match = pending.find(one => one.text === e.text) ?? pending.find(one => one.turnId === undefined)
659    if (match !== undefined) {
660      pending = pending.filter(one => one !== match)
661      // A lost folder costs only the project, never the count.
662      current = { turnId: e.turnId, uses: [], cwd: await $.session.cwd().catch(() => '') }
663    } else {
664      current = null
665    }
666
667    return next(e)
668  }).catch(($, e, next) => next(e))
669
670  // Helper agents' tool calls count toward the request that started them.
671  on('tool.call', ($, e, next) => {
672    if (current !== null && current.uses.length < 300) {
673      const input = e as unknown as Record<string, unknown>
674      current.uses.push({ tool: String(e.tool), paths: pathsOf(input), lines: writtenLines(input) })
675    }
676
677    return next(e)
678  }).catch(($, e, next) => next(e))
679
680  on('turn.complete', async ($, e, next) => {
681    if (e.agentId === undefined && current !== null && current.turnId === e.turnId) {
682      const task = current
683      current = null
684      if (e.reason === 'answer') {
685        try {
686          const model = modelName(e.usage?.model ?? (await $.session.model()))
687          const kind = kindOf(task.uses)
688          await record($, kind, model, projectOfTask(task.cwd, task.uses, home), kind === 'building' ? taskLines(task.uses) : 0)
689        } catch {
690          // a lost count is better than a stuck turn
691        }
692      }
693    }
694
695    return next(e)
696  }).catch(($, e, next) => next(e))
697
698  // The status bar button, drawn after whatever else the footer holds (the
699  // engine's mode labels, other mods' buttons), so they sit side by side.
700  on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
701    const below = await next(e)
702    const { Box, Button, Text } = $.ui.resolve(e)
703    const days = await getDays($)
704    const count = tasksOn(days[await todayOf($)])
705    const label = count === 0 ? 'Work report' : `Work report · ${count} today`
706
707    return (
708      <Box flexDirection="row" gap={2}>
709        {below}
710        <Button key="open-work-report" plain onPress={act(() => openReport($))}>
711          <Text dimColor>{label}</Text>
712        </Button>
713      </Box>
714    )
715  })
716
717  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
718    const table = $.ui.resolve(e)
719    const kit: Kit = { Box: table.Box, Text: table.Text, Button: table.Button }
720    const { Box, Text, Button } = kit
721    const width = Math.max(10, e.props.bodyColumns)
722
723    const tab = await getTab($)
724    const days = await getDays($)
725    const settings = await getSettings($)
726    const manual = await getManual($)
727    const today = await todayOf($)
728
729    const { name, dates } = titleOf(tab, today)
730    const totals = sumDays(days, daysOf(tab, today), manual)
731    const isEmpty = totals.tasks === 0 && totals.manualMinutes === 0
732    const footnote = `Estimates: minutes saved per task, building software at ${settings.buildRate} lines of code an hour, at $${settings.rate} an hour.`
733    const bars = barsOf(tab, days, today)
734    const hasChart = bars.some(bar => bar.value > 0)
735
736    // The desktop and other app surfaces set text in a proportional font: they get the SVG drawing.
737    if (e.surface !== 'terminal' && 'Svg' in table) {
738      const { Svg } = table
739      const px = pixelsFor(e.props.bodyColumns)
740      const picture = (key: string, drawing: Drawing) => (
741        <Box key={key} marginTop={1}>
742          <Svg source={drawing.source} alt={drawing.alt} />
743        </Box>
744      )
745      const models = Object.entries(totals.models)
746        .sort((a, b) => b[1] - a[1])
747        .slice(0, 6)
748        .map(([model, n], i) => ({ label: model, value: n, color: MODEL_COLORS[i % MODEL_COLORS.length]!, figures: [String(n)] }))
749      const isStreak = (tab === 'today' || tab === 'week') && streak(days, today) > 0
750      const first = shortDate(addDays(today, -29))
751
752      return (
753        <Box flexDirection="column">
754          <Box flexDirection="row" gap={1}>
755            {TABS.map(one => (
756              <Button
757                key={`tab-${one}`}
758                variant={one === tab ? 'primary' : 'secondary'}
759                onPress={act(async () => {
760                  await loadDays($)
761                  await $.state.set(TAB, one)
762                })}
763              >
764                {TAB_LABEL[one]}
765              </Button>
766            ))}
767          </Box>
768          {picture('header', headerSvg(px, name, dates))}
769          {isEmpty ? (
770            <Box marginTop={1}>
771              <Text color={MUTED}>{emptyText(tab)}</Text>
772            </Box>
773          ) : (
774            <Box flexDirection="column">
775              {picture('tiles', tilesSvg(px, totals, settings))}
776              <Text color={MUTED}>{footnote}</Text>
777              {picture('kinds', barRowsSvg(px, 'Where the time went · est. hours', kindRows(totals, settings, KIND_COLOR)))}
778              {projectRows(totals, settings).length > 0 &&
779                picture('projects', barRowsSvg(px, 'By project · est. hours', projectBarRows(totals, settings, MODEL_COLORS)))}
780              {models.length > 0 && picture('models', barRowsSvg(px, 'Who did the work', models))}
781            </Box>
782          )}
783          {hasChart && picture('chart', chartSvg(px, tab, CHART_HEADING[tab], bars, first))}
784          {hasChart && (
785            <Box marginTop={1}>
786              <Text color={isStreak ? GREEN : TEXT}>{summaryOf(tab, days, today)}</Text>
787            </Box>
788          )}
789          <Box marginTop={1}>
790            <Button key="close" dimColor onPress={act(() => $.ui.close({ id: PANE }))}>
791              Close
792            </Button>
793          </Box>
794        </Box>
795      )
796    }
797
798    return (
799      <Box flexDirection="column" width={width}>
800        {drawTabs($, kit, width, tab)}
801        {drawTitle(kit, width, name, dates)}
802        {isEmpty ? (
803          <Box flexDirection="column" marginTop={1} width={width}>
804            {wrap(emptyText(tab), width).map(line => (
805              <Text color={MUTED}>{line}</Text>
806            ))}
807          </Box>
808        ) : (
809          <Box flexDirection="column" width={width}>
810            {drawTiles(kit, width, totals, settings)}
811            {wrap(footnote, width).map(line => (
812              <Text color={MUTED}>{line}</Text>
813            ))}
814            {drawKinds(kit, width, totals, settings)}
815            {drawProjects(kit, width, totals, settings)}
816            {Object.keys(totals.models).length > 0 && drawModels(kit, width, totals)}
817          </Box>
818        )}
819        {hasChart && drawChart(kit, width, tab, bars, today)}
820        {hasChart && (
821          <Box flexDirection="column" marginTop={1} width={width}>
822            {wrap(summaryOf(tab, days, today), width).map(line => (
823              <Text color={(tab === 'today' || tab === 'week') && streak(days, today) > 0 ? GREEN : TEXT}>{line}</Text>
824            ))}
825          </Box>
826        )}
827        <Box marginTop={1} width={width}>
828          {drawChips(kit, [{ key: 'close', label: 'Close', tone: 'quiet', onPress: act(() => $.ui.close({ id: PANE })) }], width)}
829        </Box>
830      </Box>
831    )
832  })
833}
834
hooks/logic.ts 760 lines
1import type { DayRecord, Kind, ManualEntry, ProjectDay, Settings, Tab } from '../types'
2
3// ---------------------------------------------------------------- kinds
4
5export const KINDS: readonly Kind[] = ['emails', 'documents', 'building', 'media', 'research', 'other']
6
7export const KIND_LABEL: Record<Kind, string> = {
8  emails: 'Emails',
9  documents: 'Documents',
10  building: 'Building software',
11  media: 'Images and video',
12  research: 'Research',
13  other: 'Other',
14}
15
16// Building is sized by the code it wrote: lines divided by buildRate (lines an
17// hour), and never less than minutes.building per task.
18export const DEFAULT_SETTINGS: Settings = {
19  rate: 50,
20  minutes: { emails: 10, documents: 30, building: 30, media: 20, research: 25, other: 10 },
21  buildRate: 25,
22}
23
24// Reads whatever was kept, filling anything missing or broken with the default.
25export const readSettings = (kept: unknown): Settings => {
26  const out: Settings = { rate: DEFAULT_SETTINGS.rate, minutes: { ...DEFAULT_SETTINGS.minutes }, buildRate: DEFAULT_SETTINGS.buildRate }
27  if (kept === null || typeof kept !== 'object') return out
28  const raw = kept as { rate?: unknown; minutes?: Record<string, unknown>; buildRate?: unknown }
29  if (typeof raw.rate === 'number' && Number.isFinite(raw.rate) && raw.rate >= 0) out.rate = raw.rate
30  if (typeof raw.buildRate === 'number' && Number.isFinite(raw.buildRate) && raw.buildRate > 0) out.buildRate = raw.buildRate
31  for (const kind of KINDS) {
32    const value = raw.minutes?.[kind]
33    if (typeof value === 'number' && Number.isFinite(value) && value >= 0) out.minutes[kind] = value
34  }
35
36  return out
37}
38
39// ---------------------------------------------------------------- what counts
40
41// The prompts the person typed: at the terminal, in the desktop app (an SDK
42// host), from the phone, or a mod sending their own words. An image sent with
43// no words counts too. Slash commands, notifications, scheduled runs and other
44// sessions' messages do not.
45export const isTypedPrompt = (prompt: { originKind: string; asUser?: boolean; text: string; hasAttachments?: boolean }): boolean => {
46  const text = prompt.text.trim()
47  if (text.startsWith('/') || (text === '' && prompt.hasAttachments !== true)) return false
48  if (prompt.originKind === 'plugin') return prompt.asUser === true
49
50  return prompt.originKind === 'composer' || prompt.originKind === 'bridge' || prompt.originKind === 'sdk'
51}
52
53// A tool call as the sorting reads it: its name, the paths (or shell command)
54// it names, and how many lines of text it wrote, for a tool that writes.
55export type ToolUse = { tool: string; paths: string[]; lines?: number }
56
57const MEDIA_FILE = /\.(png|jpe?g|gif|webp|heic|heif|tiff?|bmp|svg|psd|dng|cr[23]|nef|arw|raw|mp4|mov|m4v|webm|avi|mkv|prproj|aep)$/i
58const DOC_FILE = /\.(docx?|pptx?|xlsx?|csv|pdf|md|markdown|txt|rtf|odt|ods|odp|pages|key|numbers)$/i
59const WRITES = /^(Write|Edit|MultiEdit|NotebookEdit)$|create|write|save|export|upload/i
60const FILE_WRITES = /^(Write|Edit|MultiEdit|NotebookEdit)$/
61export const CODE_FILE = /\.(tsx?|jsx?|mjs|cjs|mts|cts|py|rb|go|rs|java|kt|swift|cs|php|sh|zsh|bash|ps1|psm1|sql|html?|css|scss|less|vue|svelte|json|jsonc|ya?ml|toml|ini|ipynb)$/i
62const BUILD_COMMAND =
63  /\b(npm|npx|pnpm|yarn|bun|node|deno|wrangler|pytest|vitest|jest|tsc|docker|az|terraform|pip3?|uv|cargo|go (build|test|run)|git (commit|push)|gh (pr|repo|release)|claude plugin|(?:python3?|py) [\w./\\:-]+\.py)\b/
64// Remotion projects are video production, whatever the file type.
65const REMOTION_PATH = /remotion/i
66
67const EMAIL_TOOL = /mail|inbox|outlook_.*draft/i
68const MEDIA_TOOL =
69  /image|video|photo|thumbnail|remotion|frame_?io|youtube|vidiq|firefly|premiere|blender|instagram|reel|quick_cut|animate_design|remove.background/i
70const MEDIA_COMMAND = /\b(ffmpeg|ffprobe|magick|sips|remotion)\b/
71const DOC_TOOL = /document|docx|pptx|xlsx|slide|presentation|spreadsheet|sheet|excel|powerpoint|word|pdf|pandadoc/i
72const RESEARCH_TOOL =
73  /^(WebSearch|WebFetch)$|web_?search|web_?fetch|get_page_text|read_page|transcript|fetch_url|scrape|crawl|apify|deep_research/i
74
75// The words "password" and "keyword" are not about Word documents.
76const docName = (tool: string) => tool.replace(/password|keyword/gi, '')
77
78// One kind per task, by the tools it used. When a task used several kinds of
79// tool, the first that matches in this order wins: emails, images and video,
80// building software, documents, research. A task that matched none is Other.
81export const kindOf = (uses: readonly ToolUse[]): Kind => {
82  // Image or video tools, saving an image or video file, or running a media
83  // command. Reading, listing or merely naming an image file is not image work.
84  const media = (use: ToolUse) =>
85    MEDIA_TOOL.test(use.tool) ||
86    (WRITES.test(use.tool) && use.paths.some(path => MEDIA_FILE.test(path))) ||
87    (use.tool === 'Bash' && use.paths.some(path => MEDIA_COMMAND.test(path))) ||
88    (FILE_WRITES.test(use.tool) && use.paths.some(path => REMOTION_PATH.test(path)))
89  // Writing code, or running a build, test or deploy command.
90  const building = (use: ToolUse) =>
91    (FILE_WRITES.test(use.tool) && use.paths.some(path => CODE_FILE.test(path))) ||
92    (use.tool === 'Bash' && use.paths.some(path => BUILD_COMMAND.test(path)))
93  const documents = (use: ToolUse) =>
94    DOC_TOOL.test(docName(use.tool)) || (WRITES.test(use.tool) && use.paths.some(path => DOC_FILE.test(path)))
95
96  if (uses.some(use => EMAIL_TOOL.test(use.tool))) return 'emails'
97  if (uses.some(media)) return 'media'
98  if (uses.some(building)) return 'building'
99  if (uses.some(documents)) return 'documents'
100  if (uses.some(use => RESEARCH_TOOL.test(use.tool))) return 'research'
101
102  return 'other'
103}
104
105// The file paths a tool call names, and a shell command's text.
106export const pathsOf = (input: Record<string, unknown>): string[] => {
107  const found: string[] = []
108  for (const [key, value] of Object.entries(input)) {
109    if (typeof value !== 'string' || value === '') continue
110    if (/path|file/i.test(key) || key === 'command') found.push(value.trim())
111  }
112
113  return found.slice(0, 20)
114}
115
116// How many lines a writing tool's input writes: a new file's content, an
117// edit's replacement text, each edit of a multi-edit, a notebook cell.
118export const writtenLines = (input: Record<string, unknown>): number => {
119  const count = (text: unknown) => (typeof text === 'string' && text !== '' ? text.split('\n').length : 0)
120  const edits = Array.isArray(input.edits) ? (input.edits as { new_string?: unknown }[]) : []
121
122  return count(input.content) + count(input.new_string) + count(input.new_source) + edits.reduce((n, edit) => n + count(edit?.new_string), 0)
123}
124
125// The lines of code a task wrote: a file written whole counts its last
126// version once; edits add their new lines. Files that are not code, and
127// Remotion video projects, count nothing.
128export const taskLines = (uses: readonly ToolUse[]): number => {
129  const whole = new Map<string, number>()
130  const edited = new Map<string, number>()
131  for (const use of uses) {
132    if (!FILE_WRITES.test(use.tool)) continue
133    const file = use.paths.find(path => CODE_FILE.test(path) && !REMOTION_PATH.test(path))
134    if (file === undefined) continue
135    const lines = Math.max(0, Math.round(use.lines ?? 0))
136    if (use.tool === 'Write') {
137      whole.set(file, lines)
138      edited.delete(file)
139    } else edited.set(file, (edited.get(file) ?? 0) + lines)
140  }
141
142  return [...whole.values(), ...edited.values()].reduce((n, lines) => n + lines, 0)
143}
144
145// Windows paths arrive as C:\Users\name\... ; every rule below reads them
146// with forward slashes.
147const slashed = (path: string) => path.replace(/\\/g, '/')
148const WIN_DRIVE = /^[A-Za-z]:(?:\/|$)/
149
150export const isAbsolutePath = (path: string) => slashed(path).startsWith('/') || WIN_DRIVE.test(slashed(path))
151
152// A folder on a Windows drive: under home, the dev root at the drive's top
153// (D:\dev\<repo>), another top folder, or Users\<name>\<folder>.
154const windowsProject = (path: string, base: string): string => {
155  const low = path.toLowerCase()
156  const home = base.toLowerCase()
157  if (home !== '' && low === home) return 'home folder'
158  if (home !== '' && low.startsWith(`${home}/`)) return path.slice(base.length + 1).split('/')[0]!
159  const dev = /^[A-Za-z]:\/dev(?:\/([^/]+))?/i.exec(path)
160  if (dev) return dev[1] ?? 'dev workspace'
161  const user = /^[A-Za-z]:\/Users\/[^/]+\/([^/]+)/i.exec(path)
162  if (user) return user[1]!
163  const top = /^[A-Za-z]:\/([^/]+)/.exec(path)
164
165  return top ? top[1]! : 'unknown'
166}
167
168// The project a session works in, named by its folder: the repo under a dev
169// root (/Volumes/<drive>/dev/<repo>), a top folder on another drive, or the
170// first folder under home. Windows paths follow the same rules.
171export const projectOf = (cwd: string, home = ''): string => {
172  const path = slashed(cwd).replace(/\/+$/, '')
173  const base = slashed(home).replace(/\/+$/, '')
174  if (WIN_DRIVE.test(path)) return windowsProject(path, base)
175  const dev = /^\/Volumes\/[^/]+\/dev(?:\/([^/]+))?/.exec(path)
176  if (dev) return dev[1] ?? 'dev workspace'
177  const drive = /^\/Volumes\/[^/]+\/([^/]+)/.exec(path)
178  if (drive) return drive[1]!
179  if (base !== '' && path === base) return 'home folder'
180  if (base !== '' && path.startsWith(`${base}/`)) return path.slice(base.length + 1).split('/')[0]!
181
182  return path.split('/').pop() || 'unknown'
183}
184
185// A task's project: where most of the files it wrote live, else the folder
186// it ran in. A session started at the dev root that builds inside one repo
187// counts toward that repo. Mods under construction count toward claude-mods.
188export const projectOfTask = (cwd: string, uses: readonly ToolUse[], home = ''): string => {
189  const tally = new Map<string, number>()
190  for (const use of uses) {
191    if (!FILE_WRITES.test(use.tool)) continue
192    for (const written of use.paths) {
193      if (!isAbsolutePath(written)) continue
194      const path = slashed(written)
195      // Mods under construction belong to claude-mods; scratch files, temp
196      // folders and Claude's own notes and settings belong to no project.
197      if (/\/\.claude\/dev-mods\//.test(path)) {
198        tally.set('claude-mods', (tally.get('claude-mods') ?? 0) + 1)
199        continue
200      }
201      if (/^\/(private|tmp|var)\/|\/Library\/|\/\.claude\//.test(path) || /^[A-Za-z]:\/(Windows|Temp|tmp)\/|\/AppData\//i.test(path)) continue
202      const name = projectOf(path.replace(/\/[^/]*$/, ''), home)
203      tally.set(name, (tally.get(name) ?? 0) + 1)
204    }
205  }
206  const best = [...tally.entries()].sort((a, b) => b[1] - a[1])[0]
207
208  return best !== undefined ? best[0] : projectOf(cwd, home)
209}
210
211// "claude-opus-5-5" reads "Opus 5.5"; an id it cannot read is kept as given.
212export const modelName = (id: string): string => {
213  const bare = id.replace(/\[[^\]]*\]/g, '').trim()
214  const older = /claude-(\d)(?:-(\d))?-(opus|sonnet|haiku)/i.exec(bare)
215  if (older) {
216    const family = older[3]!.charAt(0).toUpperCase() + older[3]!.slice(1).toLowerCase()
217
218    return `${family} ${older[1]}${older[2] ? `.${older[2]}` : ''}`
219  }
220  const named = /(opus|sonnet|haiku|fable)-(\d{1,2})(?!\d)(?:-(\d{1,2})(?!\d))?/i.exec(bare)
221  if (named) {
222    const family = named[1]!.charAt(0).toUpperCase() + named[1]!.slice(1).toLowerCase()
223
224    return `${family} ${named[2]}${named[3] ? `.${named[3]}` : ''}`
225  }
226
227  return bare === '' ? 'Unknown model' : bare
228}
229
230// ---------------------------------------------------------------- days
231
232const two = (n: number) => String(n).padStart(2, '0')
233
234export const dayKey = (date: Date): string => `${date.getFullYear()}-${two(date.getMonth() + 1)}-${two(date.getDate())}`
235
236// Local noon of a day. Days are stepped from noon, so a clock change (an hour
237// either way) never lands on the wrong date.
238export const noonOf = (key: string): Date => {
239  const [y, m, d] = key.split('-').map(Number)
240
241  return new Date(y ?? 1970, (m ?? 1) - 1, d ?? 1, 12, 0, 0, 0)
242}
243
244const DAY_MS = 86_400_000
245
246export const addDays = (key: string, n: number): string => dayKey(new Date(noonOf(key).getTime() + n * DAY_MS))
247
248// 1 for January 1.
249export const dayOfYear = (key: string): number =>
250  Math.round((noonOf(key).getTime() - noonOf(`${key.slice(0, 4)}-01-01`).getTime()) / DAY_MS) + 1
251
252// The days a tab covers, oldest first, ending today.
253export const daysOf = (tab: Tab, today: string): string[] => {
254  const count = tab === 'today' ? 1 : tab === 'week' ? 7 : tab === 'month' ? 30 : dayOfYear(today)
255
256  return Array.from({ length: count }, (_, i) => addDays(today, i - (count - 1)))
257}
258
259export const tasksOn = (day: DayRecord | undefined): number =>
260  day === undefined ? 0 : KINDS.reduce((n, kind) => n + (day.kinds[kind] ?? 0), 0)
261
262// What an estimate is worked out from: tasks of each kind, the lines each
263// Building task wrote, and hours added by hand.
264export type Bucket = { kinds: Record<Kind, number>; buildLines: number[]; manualMinutes: number }
265
266export type Totals = Bucket & {
267  tasks: number
268  models: Record<string, number>
269  projects: Record<string, Bucket & { tasks: number }>
270}
271
272const emptyKinds = (): Record<Kind, number> => ({ emails: 0, documents: 0, building: 0, media: 0, research: 0, other: 0 })
273
274const addInto = (bucket: Bucket, kinds: Partial<Record<Kind, number>>, buildLines: readonly number[] | undefined) => {
275  for (const kind of KINDS) bucket.kinds[kind] += kinds[kind] ?? 0
276  if (buildLines) bucket.buildLines.push(...buildLines)
277}
278
279// Adds the records of the given days together, with any hours added by hand
280// on those days.
281export const sumDays = (
282  days: Readonly<Record<string, DayRecord>>,
283  keys: readonly string[],
284  manual: readonly ManualEntry[] = [],
285): Totals => {
286  const totals: Totals = { kinds: emptyKinds(), buildLines: [], manualMinutes: 0, tasks: 0, models: {}, projects: {} }
287  const project = (name: string) =>
288    (totals.projects[name] ??= { kinds: emptyKinds(), buildLines: [], manualMinutes: 0, tasks: 0 })
289  const inRange = new Set(keys)
290  for (const key of keys) {
291    const day = days[key]
292    if (day === undefined) continue
293    addInto(totals, day.kinds, day.buildLines)
294    for (const [model, n] of Object.entries(day.models)) totals.models[model] = (totals.models[model] ?? 0) + n
295    for (const [name, share] of Object.entries(day.projects ?? {})) {
296      const one = project(name)
297      addInto(one, share.kinds, share.buildLines)
298      one.tasks += KINDS.reduce((n, kind) => n + (share.kinds[kind] ?? 0), 0)
299    }
300  }
301  for (const entry of manual) {
302    if (!inRange.has(entry.date)) continue
303    totals.manualMinutes += entry.hours * 60
304    project(entry.project).manualMinutes += entry.hours * 60
305  }
306  totals.tasks = KINDS.reduce((n, kind) => n + totals.kinds[kind], 0)
307
308  return totals
309}
310
311// One finished task added to a day's record, and to its project's share.
312export const addTask = (day: DayRecord | undefined, kind: Kind, model: string, project?: string, lines = 0): DayRecord => {
313  const next: DayRecord = {
314    kinds: { ...(day?.kinds ?? {}), [kind]: (day?.kinds[kind] ?? 0) + 1 },
315    models: { ...(day?.models ?? {}), [model]: (day?.models[model] ?? 0) + 1 },
316  }
317  const buildLines = kind === 'building' ? [...(day?.buildLines ?? []), Math.max(0, Math.round(lines))] : day?.buildLines
318  if (buildLines !== undefined && buildLines.length > 0) next.buildLines = buildLines
319  const projects = { ...(day?.projects ?? {}) }
320  if (project !== undefined && project !== '') {
321    const share: ProjectDay = projects[project] ?? { kinds: {} }
322    projects[project] = {
323      kinds: { ...share.kinds, [kind]: (share.kinds[kind] ?? 0) + 1 },
324      ...(kind === 'building'
325        ? { buildLines: [...(share.buildLines ?? []), Math.max(0, Math.round(lines))] }
326        : share.buildLines
327          ? { buildLines: share.buildLines }
328          : {}),
329    }
330  }
331  if (Object.keys(projects).length > 0) next.projects = projects
332
333  return next
334}
335
336const readCounts = (raw: Record<string, unknown> | undefined): Partial<Record<Kind, number>> => {
337  const kinds: Partial<Record<Kind, number>> = {}
338  for (const kind of KINDS) {
339    const n = raw?.[kind]
340    if (typeof n === 'number' && n > 0) kinds[kind] = Math.round(n)
341  }
342
343  return kinds
344}
345
346const readLines = (raw: unknown): number[] | undefined =>
347  Array.isArray(raw) ? raw.filter((n): n is number => typeof n === 'number' && n >= 0).map(Math.round) : undefined
348
349// Reads a kept day, dropping anything that is not a count.
350export const readDay = (kept: unknown): DayRecord | undefined => {
351  if (kept === null || typeof kept !== 'object') return undefined
352  const raw = kept as { kinds?: Record<string, unknown>; models?: Record<string, unknown>; buildLines?: unknown; projects?: Record<string, unknown> }
353  const day: DayRecord = { kinds: readCounts(raw.kinds), models: {} }
354  for (const [model, n] of Object.entries(raw.models ?? {})) {
355    if (typeof n === 'number' && n > 0) day.models[model] = Math.round(n)
356  }
357  const buildLines = readLines(raw.buildLines)
358  if (buildLines && buildLines.length > 0) day.buildLines = buildLines
359  const projects: Record<string, ProjectDay> = {}
360  for (const [name, share] of Object.entries(raw.projects ?? {})) {
361    if (share === null || typeof share !== 'object') continue
362    const one = share as { kinds?: Record<string, unknown>; buildLines?: unknown }
363    const lines = readLines(one.buildLines)
364    projects[name] = { kinds: readCounts(one.kinds), ...(lines && lines.length > 0 ? { buildLines: lines } : {}) }
365  }
366  if (Object.keys(projects).length > 0) day.projects = projects
367
368  return day
369}
370
371// Days in a row with at least one task, ending today. A day with nothing yet
372// does not break the streak until it is over, so the count runs to yesterday.
373export const streak = (days: Readonly<Record<string, DayRecord>>, today: string): number => {
374  let key = tasksOn(days[today]) > 0 ? today : addDays(today, -1)
375  let n = 0
376  while (tasksOn(days[key]) > 0 && n < 3700) {
377    n += 1
378    key = addDays(key, -1)
379  }
380
381  return n
382}
383
384// ---------------------------------------------------------------- the estimate
385
386// One kind's estimated minutes. Building is sized by the lines each task
387// wrote, never under the floor; the other kinds are flat minutes per task.
388export const kindMinutes = (bucket: Bucket, kind: Kind, settings: Settings): number => {
389  if (kind !== 'building') return bucket.kinds[kind] * settings.minutes[kind]
390  const floor = settings.minutes.building
391  const sized = bucket.buildLines.reduce((n, lines) => n + Math.max(floor, (lines / settings.buildRate) * 60), 0)
392  // Tasks counted before lines were recorded get the floor.
393  const unsized = Math.max(0, bucket.kinds.building - bucket.buildLines.length)
394
395  return sized + unsized * floor
396}
397
398// Everything in a bucket, hours added by hand included.
399export const minutesSaved = (bucket: Bucket, settings: Settings): number =>
400  KINDS.reduce((n, kind) => n + kindMinutes(bucket, kind, settings), 0) + bucket.manualMinutes
401
402// 0.4, 2.5, 12, 140: one decimal below ten, whole hours after.
403export const hoursText = (minutes: number): string => {
404  const hours = minutes / 60
405  if (hours === 0) return '0'
406  if (hours < 10) return String(Math.round(hours * 10) / 10)
407
408  return String(Math.round(hours))
409}
410
411export const moneyText = (minutes: number, rate: number, commas = false): string => {
412  const dollars = Math.round((minutes / 60) * rate)
413
414  return `$${commas ? dollars.toLocaleString('en-US') : String(dollars)}`
415}
416
417// ---------------------------------------------------------------- titles
418
419const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
420const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
421
422export const shortDate = (key: string): string => {
423  const date = noonOf(key)
424
425  return `${MONTHS[date.getMonth()]!.slice(0, 3)} ${date.getDate()}`
426}
427
428export const titleOf = (tab: Tab, today: string): { name: string; dates: string } => {
429  const first = daysOf(tab, today)[0] ?? today
430  if (tab === 'today') return { name: 'TODAY', dates: `${WEEKDAYS[noonOf(today).getDay()]}, ${shortDate(today)}` }
431  if (tab === 'week') return { name: 'LAST 7 DAYS', dates: `${shortDate(first)} to ${shortDate(today)}` }
432  if (tab === 'month') return { name: 'LAST 30 DAYS', dates: `${shortDate(first)} to ${shortDate(today)}` }
433
434  return { name: `${today.slice(0, 4)} SO FAR`, dates: `Jan 1 to ${shortDate(today)}` }
435}
436
437export const emptyText = (tab: Tab): string =>
438  tab === 'today'
439    ? 'Nothing finished yet today. Your first finished task shows up here.'
440    : tab === 'week'
441      ? 'Nothing finished in the last 7 days. Your first finished task shows up here.'
442      : tab === 'month'
443        ? 'Nothing finished in the last 30 days. Your first finished task shows up here.'
444        : 'Nothing finished this year. Your first finished task shows up here.'
445
446// ---------------------------------------------------------------- the chart
447
448export type Bar = { label: string; value: number; isCurrent: boolean; isFuture: boolean }
449
450// Today and Week: the last seven days by weekday. Month: thirty daily bars.
451// Year: January through December, the months still to come left empty.
452export const barsOf = (tab: Tab, days: Readonly<Record<string, DayRecord>>, today: string): Bar[] => {
453  if (tab === 'today' || tab === 'week' || tab === 'month') {
454    return daysOf(tab === 'month' ? 'month' : 'week', today).map(key => ({
455      label: WEEKDAYS[noonOf(key).getDay()]!.slice(0, 2),
456      value: tasksOn(days[key]),
457      isCurrent: key === today,
458      isFuture: false,
459    }))
460  }
461  const year = today.slice(0, 4)
462  const month = Number(today.slice(5, 7))
463
464  return MONTHS.map((name, i) => ({
465    label: name.charAt(0),
466    value: Object.entries(days)
467      .filter(([key]) => key.startsWith(`${year}-${two(i + 1)}-`))
468      .reduce((n, [, day]) => n + tasksOn(day), 0),
469    isCurrent: i + 1 === month,
470    isFuture: i + 1 > month,
471  }))
472}
473
474const EIGHTHS = [' ', '▁', '▂', '▃', '▄', '▅', '▆', '▇', '█']
475
476// One character per bar per row, top row first: three rows, 24 steps.
477export const barCells = (value: number, max: number): [string, string, string] => {
478  const steps = max <= 0 || value <= 0 ? 0 : Math.max(1, Math.round((value / max) * 24))
479  const cell = (row: number) => EIGHTHS[Math.max(0, Math.min(8, steps - row * 8))]!
480
481  return [cell(2), cell(1), cell(0)]
482}
483
484// The line under the chart.
485export const summaryOf = (tab: Tab, days: Readonly<Record<string, DayRecord>>, today: string): string => {
486  if (tab === 'today' || tab === 'week') {
487    const n = streak(days, today)
488    if (n === 0) return 'No streak yet. Finish a task today to start one.'
489
490    return n === 1 ? 'Streak: 1 day.' : `Streak: ${n} days in a row.`
491  }
492  const keys = daysOf(tab, today)
493  const active = keys.filter(key => tasksOn(days[key]) > 0).length
494  const activeText = active === 1 ? '1 active day' : `${active} active days`
495  if (active === 0) return 'No active days yet.'
496
497  if (tab === 'month') {
498    const best = keys.reduce((a, b) => (tasksOn(days[b]) >= tasksOn(days[a]) ? b : a))
499    const n = tasksOn(days[best])
500
501    return `Best day ${shortDate(best)}, ${n} ${n === 1 ? 'task' : 'tasks'}. ${activeText}.`
502  }
503  const bars = barsOf('year', days, today)
504  const best = bars.reduce((a, b) => (b.value >= a.value ? b : a))
505  const index = bars.indexOf(best)
506
507  return `Best month ${MONTHS[index]}, ${best.value} ${best.value === 1 ? 'task' : 'tasks'}. ${activeText}.`
508}
509
510// ---------------------------------------------------------------- settings
511
512const SETTING_NAMES: Record<string, 'rate' | 'buildRate' | Kind> = {
513  rate: 'rate',
514  hourly: 'rate',
515  email: 'emails',
516  emails: 'emails',
517  document: 'documents',
518  documents: 'documents',
519  docs: 'documents',
520  building: 'building',
521  build: 'building',
522  code: 'building',
523  buildrate: 'buildRate',
524  lines: 'buildRate',
525  image: 'media',
526  images: 'media',
527  video: 'media',
528  media: 'media',
529  research: 'research',
530  other: 'other',
531}
532
533const NAMES_TEXT = 'rate, buildrate, emails, documents, building, images, research, other'
534
535export const settingsText = (settings: Settings): string =>
536  [
537    'Work Report settings. Hours and dollars are estimates.',
538    `  Hourly rate: $${settings.rate}`,
539    `  Minutes saved per task: ${KINDS.filter(kind => kind !== 'building').map(kind => `${KIND_LABEL[kind]} ${settings.minutes[kind]}`).join(', ')}`,
540    `  Building software: lines of code written ÷ ${settings.buildRate} an hour, at least ${settings.minutes.building} minutes a task`,
541    'Change one with /report settings rate 75, /report settings emails 15 or /report settings buildrate 40.',
542    `Names: ${NAMES_TEXT}.`,
543  ].join('\n')
544
545// `/report settings ...`: lists them, or changes one and says what changed.
546export const applySetting = (args: string, settings: Settings): { settings?: Settings; text: string } => {
547  const words = args.trim().split(/\s+/).filter(Boolean)
548  if (words.length === 0) return { text: settingsText(settings) }
549
550  const name = SETTING_NAMES[words[0]!.toLowerCase()]
551  if (name === undefined) {
552    return { text: `There is no setting called "${words[0]}". Use ${NAMES_TEXT}.` }
553  }
554  const raw = (words[1] ?? '').replace(/^\$/, '')
555  const value = Number(raw)
556  const [low, cap] = name === 'rate' ? [0, 10000] : name === 'buildRate' ? [1, 1000] : [0, 480]
557  if (raw === '' || !Number.isFinite(value) || value < low || value > cap) {
558    return {
559      text:
560        name === 'rate'
561          ? 'Give the hourly rate as a number from 0 to 10000, like /report settings rate 75.'
562          : name === 'buildRate'
563            ? 'Give the lines of code an hour as a number from 1 to 1000, like /report settings buildrate 40.'
564            : `Give the minutes as a number from 0 to 480, like /report settings ${words[0]!.toLowerCase()} 15.`,
565    }
566  }
567  const rounded = Math.round(value * 100) / 100
568
569  if (name === 'rate') {
570    return { settings: { ...settings, rate: rounded }, text: `Hourly rate is now $${rounded}. The report uses it from now on, for every day.` }
571  }
572  if (name === 'buildRate') {
573    return {
574      settings: { ...settings, buildRate: rounded },
575      text: `Building software is now estimated at ${rounded} lines of code an hour, for every day.`,
576    }
577  }
578  if (name === 'building') {
579    return {
580      settings: { ...settings, minutes: { ...settings.minutes, building: rounded } },
581      text: `Every Building software task now counts as at least ${rounded} minutes, for every day.`,
582    }
583  }
584
585  return {
586    settings: { ...settings, minutes: { ...settings.minutes, [name]: rounded } },
587    text: `${KIND_LABEL[name]} now count as ${rounded} minutes saved per task, for every day.`,
588  }
589}
590
591// ---------------------------------------------------------------- hours added by hand
592
593const DATE = /^\d{4}-\d{2}-\d{2}$/
594
595// `/report add "QBR builder" 160 2026-05-01`: a project (quoted, or the words
596// before the hours), the hours, and an optional date (today when left out).
597export const parseAdd = (args: string, today: string): { entry?: Omit<ManualEntry, 'id'>; text?: string } => {
598  const usage = 'Try /report add "QBR builder" 160 2026-05-01: the project, the hours, and a date if it was not today.'
599  const quoted = /^\s*["“]([^"”]+)["”]\s*(.*)$/.exec(args)
600  let project: string
601  let rest: string[]
602  if (quoted) {
603    project = quoted[1]!.trim()
604    rest = quoted[2]!.trim().split(/\s+/).filter(Boolean)
605  } else {
606    const words = args.trim().split(/\s+/).filter(Boolean)
607    const at = words.findIndex(word => /^\d+(\.\d+)?h?$/i.test(word))
608    if (at <= 0) return { text: usage }
609    project = words.slice(0, at).join(' ')
610    rest = words.slice(at)
611  }
612  const hours = Number((rest[0] ?? '').replace(/h$/i, ''))
613  if (project === '' || !Number.isFinite(hours) || hours <= 0 || hours > 5000) return { text: usage }
614  const date = rest[1] ?? today
615  if (!DATE.test(date) || dayKey(noonOf(date)) !== date) return { text: 'Give the date as year-month-day, like 2026-05-01.' }
616  if (date > today) return { text: 'That date is in the future. Add hours for work already done.' }
617
618  return { entry: { project: project.slice(0, 60), hours: Math.round(hours * 10) / 10, date } }
619}
620
621export const readManual = (kept: unknown): ManualEntry[] =>
622  Array.isArray(kept)
623    ? kept.filter(
624        (one): one is ManualEntry =>
625          typeof one === 'object' &&
626          one !== null &&
627          typeof one.id === 'string' &&
628          typeof one.project === 'string' &&
629          typeof one.hours === 'number' &&
630          typeof one.date === 'string' &&
631          DATE.test(one.date),
632      )
633    : []
634
635export const manualListText = (list: readonly ManualEntry[]): string =>
636  list.length === 0
637    ? 'No hours added by hand yet. Add one with /report add "QBR builder" 160 2026-05-01.'
638    : [
639        'Hours you added by hand (estimates):',
640        ...list.map((one, i) => `  ${i + 1}. ${one.project}: ${one.hours} h on ${one.date}`),
641        'Remove one with /report remove 2.',
642      ].join('\n')
643
644// ---------------------------------------------------------------- by project
645
646export type ProjectRow = { name: string; minutes: number; tasks: number }
647
648// Projects by estimated time, the top ones by name and the rest together.
649export const projectRows = (totals: Totals, settings: Settings, top = 8): ProjectRow[] => {
650  const rows = Object.entries(totals.projects)
651    .map(([name, bucket]) => ({ name, minutes: minutesSaved(bucket, settings), tasks: bucket.tasks }))
652    .filter(row => row.minutes > 0 || row.tasks > 0)
653    .sort((a, b) => b.minutes - a.minutes || b.tasks - a.tasks)
654  if (rows.length <= top) return rows
655  const rest = rows.slice(top - 1)
656
657  return [
658    ...rows.slice(0, top - 1),
659    { name: `${rest.length} other projects`, minutes: rest.reduce((n, row) => n + row.minutes, 0), tasks: rest.reduce((n, row) => n + row.tasks, 0) },
660  ]
661}
662
663// ---------------------------------------------------------------- drawing helpers
664
665export const clip = (text: string, width: number): string =>
666  width <= 0 ? '' : text.length <= width ? text : `${text.slice(0, Math.max(0, width - 1))}…`
667
668// Breaks text into lines no wider than `width`, so nothing is left to wrap.
669export const wrap = (text: string, width: number): string[] => {
670  const room = Math.max(1, width)
671  const lines: string[] = []
672  let line = ''
673  for (const word of text.split(/\s+/).filter(Boolean)) {
674    let rest = word
675    while (rest.length > room) {
676      if (line !== '') lines.push(line)
677      line = ''
678      lines.push(rest.slice(0, room))
679      rest = rest.slice(room)
680    }
681    if (line === '') line = rest
682    else if (line.length + 1 + rest.length <= room) line = `${line} ${rest}`
683    else {
684      lines.push(line)
685      line = rest
686    }
687  }
688  if (line !== '') lines.push(line)
689
690  return lines
691}
692
693// Characters three rows tall in heavy box-drawing strokes.
694const GLYPHS: Record<string, [string, string, string]> = {
695  '0': ['┏━┓', '┃ ┃', '┗━┛'],
696  '1': ['╺┓ ', ' ┃ ', '╺┻╸'],
697  '2': ['╺━┓', '┏━┛', '┗━╸'],
698  '3': ['╺━┓', ' ━┫', '╺━┛'],
699  '4': ['╻ ╻', '┗━┫', '  ╹'],
700  '5': ['┏━╸', '┗━┓', '╺━┛'],
701  '6': ['┏━╸', '┣━┓', '┗━┛'],
702  '7': ['╺━┓', '  ┃', '  ╹'],
703  '8': ['┏━┓', '┣━┫', '┗━┛'],
704  '9': ['┏━┓', '┗━┫', '╺━┛'],
705  '.': [' ', ' ', '▪'],
706  $: ['┏╋╸', '┗╋┓', '╺╋┛'],
707}
708
709export const bigText = (text: string): [string, string, string] => {
710  const chars = text.split('').filter(char => GLYPHS[char] !== undefined)
711  const rows: [string, string, string] = ['', '', '']
712  for (const row of [0, 1, 2] as const) rows[row] = chars.map(char => GLYPHS[char]![row]).join(' ')
713
714  return rows
715}
716
717// How many tiles sit side by side: three, then two, then one.
718export const tilesPerRow = (width: number, widest: number, count = 3): number => {
719  for (let n = count; n > 1; n--) {
720    if (n * widest + (n - 1) <= width) return n
721  }
722
723  return 1
724}
725
726// ---------------------------------------------------------------- history
727
728// One finished request as scripts/history.py prints it: when, the model, its
729// tool calls (name, paths, lines written) and the folder it ran in.
730export type PastTask = { t: number; m: string; u: [string, string[], number?][]; c?: string }
731
732export const readHistory = (text: string): PastTask[] => {
733  const raw: unknown = JSON.parse(text)
734  if (!Array.isArray(raw)) return []
735
736  return raw.filter(
737    (task): task is PastTask =>
738      typeof task === 'object' && task !== null && typeof task.t === 'number' && typeof task.m === 'string' && Array.isArray(task.u),
739  )
740}
741
742// The past requests counted into day records, sorted, sized and named by
743// project as live ones are.
744export const historyDays = (tasks: readonly PastTask[], home = ''): Record<string, DayRecord> => {
745  const days: Record<string, DayRecord> = {}
746  for (const task of tasks) {
747    const key = dayKey(new Date(task.t))
748    const uses: ToolUse[] = task.u.map(([tool, paths, lines]) => ({
749      tool: String(tool),
750      paths: Array.isArray(paths) ? paths.map(String) : [],
751      lines: typeof lines === 'number' ? lines : 0,
752    }))
753    const kind = kindOf(uses)
754    const project = typeof task.c === 'string' && task.c !== '' ? projectOfTask(task.c, uses, home) : undefined
755    days[key] = addTask(days[key], kind, modelName(task.m), project, kind === 'building' ? taskLines(uses) : 0)
756  }
757
758  return days
759}
760
hooks/desktop.ts 182 lines
1// The desktop app's drawing. It sets text in a proportional font, so rows
2// sized in character cells drift; the header, the tiles, the breakdowns and
3// the chart are drawn here as SVG instead, sized in pixels.
4
5import type { Kind, Settings, Tab } from '../types'
6import { KINDS, KIND_LABEL, hoursText, kindMinutes, minutesSaved, moneyText, projectRows } from './logic'
7import type { Bar, Totals } from './logic'
8
9const GOLD = '#F2C46D'
10const LINE = '#262B33'
11const MUTED = '#7D8590'
12const TEXT = '#E6EDF3'
13const GREEN = '#3DD68C'
14
15const SANS = `-apple-system, BlinkMacSystemFont, 'SF Pro Text', Inter, 'Segoe UI', sans-serif`
16
17export type Drawing = { source: string; alt: string }
18
19const esc = (text: string) => text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
20
21// The pixel width to draw at. The desktop reports fewer columns than it
22// shows; a column is about 13 pixels there. An SVG drawn wider than the pane
23// is scaled down to fit, never cut.
24export const pixelsFor = (columns: number): number => Math.max(260, Math.round(columns * 13))
25
26// About how wide a run of text sets, for laying things beside it.
27const textWidth = (text: string, size: number, isBold = false) => text.length * size * (isBold ? 0.64 : 0.56)
28
29const svg = (width: number, height: number, body: string) =>
30  `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" font-family="${esc(SANS)}">${body}</svg>`
31
32const label = (x: number, y: number, text: string, size: number, fill: string, extra = '') =>
33  `<text x="${x}" y="${y}" font-size="${size}" fill="${fill}"${extra}>${esc(text)}</text>`
34
35// A small muted heading in capitals, then a hairline to the edge.
36const heading = (width: number, y: number, text: string) => {
37  const caps = text.toUpperCase()
38  const end = Math.min(width, caps.length * 11 * 0.74 + 12)
39
40  return (
41    label(0, y, caps, 11, MUTED, ` letter-spacing="0.08em" font-weight="600"`) +
42    (end < width ? `<line x1="${end.toFixed(1)}" y1="${y - 4}" x2="${width}" y2="${y - 4}" stroke="${LINE}" stroke-width="1"/>` : '')
43  )
44}
45
46// The title in bold capitals, its dates on the right, and under it a gold
47// rule as wide as the title that runs on as a dim hairline to the edge.
48export const headerSvg = (width: number, name: string, dates: string): Drawing => {
49  const titleWidth = Math.min(width, textWidth(name, 16, true) * 1.08)
50  const hasDates = titleWidth + 16 + textWidth(dates, 13) <= width
51  const body =
52    `<text x="0" y="20" font-size="16" font-weight="700" letter-spacing="0.06em" fill="${TEXT}" textLength="${titleWidth.toFixed(1)}" lengthAdjust="spacing">${esc(name)}</text>` +
53    (hasDates ? label(width, 20, dates, 13, MUTED, ` text-anchor="end"`) : '') +
54    `<line x1="0" y1="33" x2="${titleWidth.toFixed(1)}" y2="33" stroke="${GOLD}" stroke-width="2"/>` +
55    `<line x1="${titleWidth.toFixed(1)}" y1="33" x2="${width}" y2="33" stroke="${LINE}" stroke-width="1"/>`
56
57  return { source: svg(width, 38, body), alt: `${name}, ${dates}` }
58}
59
60const TILE_MIN = 168
61const TILE_GAP = 12
62
63export const tilesAcross = (width: number): number => {
64  for (let n = 3; n > 1; n--) if (n * TILE_MIN + (n - 1) * TILE_GAP <= width) return n
65
66  return 1
67}
68
69// Three rounded tiles with big numerals; fewer side by side as it narrows.
70// A number too wide for the big size is set smaller, still bold.
71export const tilesSvg = (width: number, totals: Totals, settings: Settings): Drawing => {
72  const minutes = minutesSaved(totals, settings)
73  const tiles = [
74    { big: hoursText(minutes), plain: `${hoursText(minutes)} h`, label: 'EST. HOURS SAVED', color: GOLD },
75    { big: totals.tasks.toLocaleString('en-US'), plain: totals.tasks.toLocaleString('en-US'), label: 'TASKS DONE', color: TEXT },
76    { big: moneyText(minutes, settings.rate, true), plain: moneyText(minutes, settings.rate, true), label: 'EST. VALUE', color: GREEN },
77  ]
78  const across = tilesAcross(width)
79  const tileWidth = Math.floor((width - (across - 1) * TILE_GAP) / across)
80  const tileHeight = 96
81  const room = tileWidth - 32
82  let body = ''
83  tiles.forEach((tile, i) => {
84    const x = (i % across) * (tileWidth + TILE_GAP)
85    const y = Math.floor(i / across) * (tileHeight + TILE_GAP)
86    const isBig = textWidth(tile.big, 38, true) <= room
87    const size = isBig ? 38 : Math.max(14, Math.min(24, Math.floor(room / (tile.plain.length * 0.64))))
88    body +=
89      `<rect x="${x + 0.5}" y="${y + 0.5}" width="${tileWidth - 1}" height="${tileHeight - 1}" rx="12" fill="none" stroke="${LINE}"/>` +
90      `<text x="${x + 16}" y="${y + 54}" font-size="${size}" font-weight="700" fill="${tile.color}" style="font-variant-numeric: tabular-nums">${esc(isBig ? tile.big : tile.plain)}</text>` +
91      label(x + 16, y + 78, tile.label, 11, MUTED, ` letter-spacing="0.08em" font-weight="600"`)
92  })
93  const rows = Math.ceil(tiles.length / across)
94  const alt = tiles.map(tile => `${tile.label.toLowerCase()} ${tile.plain}`).join(', ')
95
96  return { source: svg(width, rows * tileHeight + (rows - 1) * TILE_GAP, body), alt }
97}
98
99export type BarRow = { label: string; value: number; color: string; figures: string[] }
100
101// A heading, then one row per item: its name, a colored bar on a dim track,
102// and its figures right-aligned.
103export const barRowsSvg = (width: number, title: string, rows: BarRow[]): Drawing => {
104  const labelWidth = Math.min(170, Math.round(width * 0.32))
105  const figureWidth = rows[0] !== undefined && rows[0].figures.length > 1 ? 112 : 44
106  const trackStart = labelWidth
107  const trackEnd = width - figureWidth - 12
108  const max = Math.max(0, ...rows.map(row => row.value))
109  let body = heading(width, 12, title)
110  rows.forEach((row, i) => {
111    const y = 36 + i * 26
112    const isZero = row.value === 0
113    const track = Math.max(0, trackEnd - trackStart)
114    const filled = max <= 0 || isZero ? 0 : Math.max(4, (row.value / max) * track)
115    body += label(0, y, row.label, 13, isZero ? MUTED : TEXT)
116    if (track >= 24) {
117      body += `<rect x="${trackStart}" y="${y - 7}" width="${track.toFixed(1)}" height="5" rx="2.5" fill="${LINE}"/>`
118      if (filled > 0) body += `<rect x="${trackStart}" y="${y - 7}" width="${filled.toFixed(1)}" height="5" rx="2.5" fill="${row.color}"/>`
119    }
120    // The last figure sits at the edge; any before it, 64 pixels in from there.
121    row.figures.forEach((figure, j) => {
122      const x = width - (row.figures.length - 1 - j) * 64
123      body += label(x, y, figure, 13, isZero ? MUTED : TEXT, ` text-anchor="end" style="font-variant-numeric: tabular-nums"`)
124    })
125  })
126  const alt = `${title}: ${rows.map(row => `${row.label} ${row.figures.join(' ')}`).join(', ')}`
127
128  return { source: svg(width, 36 + rows.length * 26 - 12, body), alt }
129}
130
131export const kindRows = (totals: Totals, settings: Settings, colors: Record<Kind, string>): BarRow[] =>
132  KINDS.map(kind => ({
133    label: KIND_LABEL[kind],
134    value: kindMinutes(totals, kind, settings),
135    color: colors[kind],
136    figures: [String(totals.kinds[kind]), `${hoursText(kindMinutes(totals, kind, settings))} h`],
137  }))
138
139// One row per project: its tasks and estimated hours, hours added by hand
140// included.
141export const projectBarRows = (totals: Totals, settings: Settings, colors: readonly string[]): BarRow[] =>
142  projectRows(totals, settings).map((row, i) => ({
143    label: row.name,
144    value: row.minutes,
145    color: colors[i % colors.length]!,
146    figures: [String(row.tasks), `${hoursText(row.minutes)} h`],
147  }))
148
149// The chart: a heading, bars on a plot 64 pixels tall, labels under them.
150// The current day or month is gold; months still to come are left empty.
151export const chartSvg = (width: number, tab: Tab, title: string, bars: Bar[], first: string): Drawing => {
152  const slot = width / bars.length
153  const barWidth = Math.max(2, Math.min(28, slot * 0.62))
154  const max = Math.max(0, ...bars.map(bar => bar.value))
155  const base = 92
156  const plot = 64
157  let body = heading(width, 12, title)
158  bars.forEach((bar, i) => {
159    const x = i * slot + (slot - barWidth) / 2
160    if (bar.isFuture) return
161    if (bar.value === 0) {
162      body += `<rect x="${x.toFixed(1)}" y="${base - 2}" width="${barWidth.toFixed(1)}" height="2" rx="1" fill="${LINE}"/>`
163
164      return
165    }
166    const tall = Math.max(4, (bar.value / max) * plot)
167    const fill = bar.isCurrent ? GOLD : MUTED
168    body += `<rect x="${x.toFixed(1)}" y="${(base - tall).toFixed(1)}" width="${barWidth.toFixed(1)}" height="${tall.toFixed(1)}" rx="${Math.min(3, barWidth / 2).toFixed(1)}" fill="${fill}"${bar.isCurrent ? '' : ' fill-opacity="0.6"'}/>`
169  })
170  if (tab === 'month') {
171    body += label(0, base + 18, first, 11, MUTED) + label(width, base + 18, 'Today', 11, GOLD, ` text-anchor="end"`)
172  } else {
173    bars.forEach((bar, i) => {
174      const x = i * slot + slot / 2
175      body += label(Number(x.toFixed(1)), base + 18, bar.label, 11, bar.isCurrent ? GOLD : MUTED, ` text-anchor="middle"`)
176    })
177  }
178  const alt = `${title}: ${bars.filter(bar => !bar.isFuture).map(bar => `${bar.label} ${bar.value}`).join(', ')}`
179
180  return { source: svg(width, base + 24, body), alt }
181}
182
types/index.d.ts 46 lines
1export type Kind = 'emails' | 'media' | 'building' | 'documents' | 'research' | 'other'
2
3// One project's share of a day: tasks of each kind, and the lines of code
4// each Building task wrote (one number per task, so the size estimate can be
5// worked out again when the settings change).
6export type ProjectDay = {
7  kinds: Partial<Record<Kind, number>>
8  buildLines?: number[]
9}
10
11// One calendar day: how many tasks of each kind, how many each model did,
12// the lines each Building task wrote, and the same split by project.
13export type DayRecord = {
14  kinds: Partial<Record<Kind, number>>
15  models: Record<string, number>
16  buildLines?: number[]
17  projects?: Record<string, ProjectDay>
18}
19
20// Hours the person added by hand for work older than the session history.
21export type ManualEntry = {
22  id: string
23  project: string
24  hours: number
25  date: string
26}
27
28export type Settings = {
29  rate: number
30  minutes: Record<Kind, number>
31  buildRate: number
32}
33
34export type Tab = 'today' | 'week' | 'month' | 'year'
35
36declare module 'claude-code' {
37  interface PluginState {
38    'work-report': {
39      days: Record<string, DayRecord>
40      settings: Settings
41      tab: Tab
42      manual: ManualEntry[]
43    }
44  }
45}
46