SLOPSHOPPER

mokkan

Cross-session reminders: /mokkan toggles a live pane with your TODOs, Reminders and Archived tabs, /mokkan <command> runs push, in, edit, ack, done and the…

panetoastpromptprocesstimer
★ 4v0.8.0MITupdated 2026-10-17vicmpen/mokkan/claude-plugin
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · mokkan
│ ┃ mokkan ✕ › fix the failing auth test and add an audit log call │ ┃ ╭──────────────────────────────────────────╮ │ ┃ │ mokkan │ ⏺ Read(src/auth.ts) │ ┃ │ TODOs 0 │ Reminders 0 │ Archived 0 │ ⎿ Read 6 lines │ ┃ │──────────────────────────────────────────│ ⏺ Update(src/auth.ts) │ ┃ │──────────── │ ⎿ Added 2 lines, removed 1 line │ ┃ │ No todos. │ ⏺ Bash(bun test) │ ┃ │ t adds one. │ ⎿ 3 pass, 1 fail │ ┃ │ │ │ ┃ │ ctrl+x tab to use keys │ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ loading… │ │ ┃ │ │ ✻ Worked for 42s · done 4:20 PM │ ┃ │ │ │ ┃ │ │ │ ┃ │ │ │ ┃ │ │ │ ┃ │ │ │ ┃ │ │ │ ┃ │ │ │ ┃ │ │ │ ┃ │ │ │ ┃ │ │ │ ┃ │ │ │ ┃ │ │ │ ┃ │ │ │ ┃ │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · mokkan
╭──────────────────────────────────────────────────────────╮ │ mokkan │ │ TODOs 0 │ Reminders 0 │ Archived 0 │ │────────────────────────────────────────────────────── │ │ No todos. │ │ t adds one. │ │ │ │ ctrl+x tab to use keys │ │ loading… │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰──────────────────────────────────────────────────────────╯
README

<h1><img src="assets/banner.svg" width="960" alt="mokkan"></h1>

A Claude Code mod for reminders that follow you between agent sessions. mokkan docks your reminder stack in a pane beside the Claude Code transcript, and the same list reaches every other session you open: Claude Code, Codex and any terminal, on any machine. Push a note in one session; it surfaces in the next one and stays there until you say you've seen it.

/plugin marketplace add vicmpen/mokkan
/plugin install mokkan@mokkan

Then /mokkan opens the pane, and closes it again; /mokkan push call the bank runs a command straight away. New to mods? Read Getting started with Claude Code mods. The tour, with a live demo, is at mokkan.dev.

One push. Every session.

The server (https://api.mokkan.dev) keeps the only copy of your list. Each session asks it what's due, not the model remembering to check, so a note pushed on your laptop shows up on your desktop within seconds:

  • The pane (/mokkan) in Claude Code lists it on its next refresh, every 15 seconds while it's open, and a scheduled reminder that comes due while it's open arrives as a toast. Nothing is injected into the conversation.
  • Codex checks at the start and end of every task, through the mokkan skill.
  • Any terminal has the same list: mokkan prints it, mokkan ui opens it full-screen.
mokkan push "check the flaky login test"
mokkan in 2h "ask Maria about the release notes"
mokkan                      # the list, top of the stack first
mokkan pop                  # remove the top one (dequeue removes the oldest)

Acknowledge once, from any session, and every session knows. A pop is a single atomic step on the server, so two sessions can never take the same item, and a popped item moves to done instead of disappearing.

Nothing closes until you say so.

Showing a reminder doesn't mean you saw it. mokkan keeps it lit until you acknowledge it, and a scheduled reminder that nobody acknowledges, or that comes due while no pane is open, is emailed to you. Todos (no due time) are never toasted or emailed.

StateWhat it means
scheduledmokkan in 1h30m … waits on the server, off the list, until its time comes.
dueOn the list and unseen. An open pane shows it as a toast within 15 seconds. With no pane open, it goes out by email.
deliveredShown as a toast in the pane. If no ack comes, the email goes out anyway.
acknowledgedYou've seen it. It stays on the stack until you pop, dequeue or finish it.

When is a reminder emailed?

Only a reminder with a due time is ever emailed, and at most once. An open pane tells the server that a session is active each time it refreshes.

When it comes dueWhat happens
A pane is openThe pane shows it as a toast within 15 seconds. If you haven't acknowledged it 3 minutes after the toast, it is emailed.
No pane has been open in the last 5 minutesThe server waits 5 minutes after the due time. If a pane opens in that window, it shows the toast and the case above applies. Otherwise it is emailed 5 minutes after the due time.
You acknowledge it first (pane a, mokkan ack, Codex)No email, and the credit held for it is given back.

The timings are the server's defaults. If you run your own server, they are ACK_GRACE_SECONDS (180), HEARTBEAT_ACTIVE_SECONDS (300) and NO_SESSION_EMAIL_DELAY_SECONDS (300). Codex and the terminal (mokkan, mokkan ui) read the same list; Codex checks at the start and end of each task through its skill.

The mod: a pane in Claude Code

The plugin ships a mod: a small TypeScript module that runs inside your Claude Code session, sees its events as they happen, and draws a pane. /mokkan opens it, and closes it when it is open. In the fullscreen layout (/tui fullscreen, the default in most terminals) the pane docks beside the transcript from 110 columns; on the main-screen layout it sits above the prompt. Esc hands the keyboard back and ctrl+x tab takes it again. While the pane has the keyboard, a key it doesn't use does nothing instead of landing in the prompt.

It is laid out like mokkan ui: the header with your credits, TODOs 2 │ Reminders 3 │ Archived 4, the list, the last result, the keys, and the sync state on the bottom line. The pane draws its own rounded border, pale green while it has the keyboard and grey while it doesn't. Three tabs, each with its own count: TODOs holds the open todos (no due time), Reminders the open reminders (a due time, scheduled ones included), both in stack order, and Archived the finished ones. The pane opens on Reminders while one is due, and on TODOs otherwise. A row's bar is cyan for a todo and magenta for a reminder; · marks an acknowledged one and ✓ an archived one. Rows are numbered within their tab. A reminder's time sits on the right and always says which way it points: in 40m, Wed 17:00, overdue 40m (red), 2h ago. The selected row gets its history underneath (todo · added 3h ago · shown 1h ago · acked 5m ago). ↑ ↓ and Tab walk the pane's buttons, and the row they land on is selected, marked with ▸ and bold; a click or a row's number selects it directly. Rows past the ninth are typed as two digits within a second (1 then 2 is row 12), and with ten or more rows 0 joins the keys for rows 10, 20 and so on. Selecting never changes anything. While the pane doesn't have the keyboard it shows ctrl+x tab to use keys in place of the commands:

KeyLabelAction
ttodoadd a todo: type what to remember (1 credit)
rreminderschedule a reminder: 2h call the bank, the first word is a duration (1 credit, +1 held for the email)
eeditedit the selected one's text; it can't be left empty (every 3rd edit costs 1 credit)
wwhenset its due time (2h), or clear it to make it a todo again
darchive / reopenarchive it (mokkan done); in Archived, reopen it
aackacknowledge it: you've seen it, so its email stops
vview reminders / view archived / view todosgo to the next tab, TODOs → Reminders → Archived; a click on a tab goes straight to it
bbuyopen Stripe Checkout in your browser to add credits (not on mobile)
s / l / qsync / log out / closesync now / log out / close the pane
hhelp / backshow what mokkan is, the glyphs, ack vs archive, and the costs in place of the list; h again goes back
l / rlog in / registerwhen logged out (the password is masked)

Archiving with Enter and logging out ask first, naming what they act on and what each answer does: archive "call the bank"?, with y: archive · n: keep underneath. While a command runs, other keys wait. The line above the commands shows each result with the reminder it touched (added · call mom, due in 2h · call the bank). The pane stays on its tab: a new or changed one that belongs on another tab says where it went (added to TODOs · call mom, moved to Reminders, due in 2h · renew the cert), errors start with error: in red and wrap so the fix at their end (Run: mokkan buy) stays readable, and the line clears itself after 15 seconds. The header's balance turns yellow under 10 credits (· 7 credits · low) and red at 0; b opens Stripe Checkout to add more. When the server can't be reached the pane keeps the last list and marks it offline · synced 12:04, the time of the last good sync; online the bottom line reads synced 12:04, and while a command runs it names it (archiving…).

The mod runs the plugin's own copy of the CLI and syncs when it opens and after every action, then 15 seconds after each sync while it is open. When a sync fails the wait doubles, up to 60 seconds, and the next good sync puts it back to 15. Each sync tells the server a session is active, and every reminder with a due time that has come due is shown as a toast and marked delivered. On Claude Code 2.1.295 or later it also raises a native notification through your Claude Code notification setting (preferredNotifChannel: iTerm2, kitty, Ghostty or the terminal bell), so you see it with the terminal behind another window; without a channel for your terminal you get the toast alone. Todos are never shown this way. Mods ship inside plugins, so there is nothing extra to install: the plugin's hooks/hooks.json names the module under modules, and that is all it holds.

Install

mokkan needs Node.js 20.3 or later. Choose the channel that matches the tools you use. All channels share the same account and the same local login (~/.config/mokkan/).

Claude Code (plugin)

/plugin marketplace add vicmpen/mokkan
/plugin install mokkan@mokkan

From a shell, run claude plugin marketplace add vicmpen/mokkan, then claude plugin install mokkan@mokkan.

The plugin provides:

  • /mokkan: on its own it opens the pane (see below), and closes it when it is open. With a command it runs it and prints the output straight away, without a model turn: /mokkan push call the bank, /mokkan in 2h stretch, /mokkan list. ui and watch need a terminal, and login and register are done in the pane (l, r) or a terminal.
  • The mokkan skill: Claude uses it when you ask it in words to remember something or to change a reminder. The slash-command menu lists /mokkan under the skill's full name, /mokkan:mokkan; typed, the two are the same.
  • A mod: the pane, with your stack beside the transcript and the same actions as mokkan ui (see below).

The plugin includes its own copy of the CLI, so you don't need the npm package, but node (20.3 or later) must be on your PATH: the plugin's command and pane run the CLI with it. To run register, login or buy, which ask for a password or open a browser, you need a terminal. Use npx @vicmpen/mokkan-cli … there, or install the npm package.

To see reminders when Claude Code isn't open, at your shell prompt and on your desktop, install the npm package and run mokkan notify setup in a terminal (see Notifications). It doesn't run from the plugin's copy of the CLI.

Terminal (npm)

npm install -g @vicmpen/mokkan-cli
mokkan help

Codex (skill)

Install the CLI with npm install -g @vicmpen/mokkan-cli, then copy or link the skill directory from this repository:

git clone https://github.com/vicmpen/mokkan
mkdir -p ~/.codex/skills
cp -r mokkan/codex ~/.codex/skills/mokkan

The npm package contains the same files under $(npm root -g)/mokkan/codex. Codex has no hooks, so the skill tells Codex to check for due reminders at the start and end of each task.

/mokkan-cli without the plugin (optional)

/mokkan is the plugin's. In sessions that don't load the plugin, the npm package gives you /mokkan-cli: copy claude-command/mokkan-cli.md from the package or from this repository to ~/.claude/commands/mokkan-cli.md. It runs mokkan from your PATH through Claude and takes the same arguments as /mokkan: /mokkan-cli push call the bank. Don't name it mokkan.md: a user-level /mokkan hides the plugin's from the slash-command menu.

Account

mokkan register you@example.com     # shows the privacy policy summary, emails you a code, then asks for a password (10+ characters)
mokkan login you@example.com
mokkan logout
mokkan status                       # who you are, server, balance
mokkan delete-account               # deletes the account and everything on it (see Privacy)

Registration and login ask for a password without showing it, so run them in a terminal. When you try them from Claude Code, the command only prints the terminal command you need. Registering shows a summary of the privacy policy first and goes on only when you answer y; the pane shows the same summary before it asks for your email.

Commands

mokkan [list] [--all]                  active list, top first (--all adds scheduled reminders)
mokkan push <text>                     add to the top
mokkan pop | dequeue                   remove from the top (LIFO) | from the bottom (FIFO)
mokkan in <duration> <text>            schedule: 30s, 10m, 2h, 1d, 1h30m
mokkan edit <n|id> [--all] [--in 2h | --at <iso> | --clear-due] [new text...]
mokkan ack <id...> | all               acknowledge reminders you have seen
mokkan done <id...> | undone <id...>   finish reminders anywhere on the list (like pop, by id) | reopen finished ones
mokkan pending | done                  due and not yet shown | finished reminders
mokkan balance | buy                   credits
mokkan feedback <text>                 send feedback to the mokkan developer (free)
mokkan ui                              full-screen view with keyboard actions (see below)
mokkan privacy [--json]                the privacy policy's version, link and summary (no login needed)
mokkan accept                          accept the current privacy policy (see Privacy)
mokkan delete-account                  delete your account, in a terminal (see Privacy)
mokkan notify setup | remove           show fired reminders at the prompt and on the desktop, in a terminal (see Notifications)
mokkan notify on|off [shell|desktop|osc]   turn notification channels on or off
mokkan notify status | test | doctor   what is set up, a test notification, details for a bug report
mokkan shell init zsh|bash|fish        print the prompt hook, for dotfiles you manage yourself

Add --json for machine-readable output. mokkan help lists everything.

Exit codes: 0 success, 1 a mistake in the command or not logged in, 2 the server is unreachable or failing (or rate limiting), 3 not enough credits (run mokkan buy), 4 the privacy policy must be accepted first (run mokkan accept in a terminal).

Acknowledging and finishing are different acts. mokkan ack says "seen": it stops the email for a due reminder and releases its reserved credit, but the reminder stays on the list. mokkan done <id> finishes a reminder anywhere on the list, exactly as pop finishes the top one; it moves to the history that mokkan done shows. mokkan undone <id> puts a finished reminder back where it was. A reopened reminder that had a due time comes back acknowledged, so it is never emailed again. Both are free.

mokkan edit changes one reminder in place. Give it the number shown by mokkan list (with --all, the number shown by mokkan list --all) or an id prefix of at least 4 characters. The new text is the rest of the words: mokkan edit 2 --in 2h call mom at 5; it can't be empty. --at needs a full ISO-8601 time with a zone (2026-10-01T09:00:00Z). Put all your changes in one call, because every call counts as one edit. A due time can be changed only while the reminder is still scheduled or due and its email has not been sent. If the list changed since you last read it, a numbered edit stops with "The list changed" and edits nothing.

Terminal UI

mokkan ui opens a full-screen view of your stack in the terminal: the same three tabs as the pane (TODOs │ Reminders │ Archived; Reminders includes scheduled ones, and it opens on Reminders while one is due), your credit balance, and key hints. Todos (pushed, no due time) show □; reminders with a due time show ◷ scheduled, ● due (yellow), ○ shown, · acknowledged, with the time on the right (in 40m, 17:00, Wed 17:00, 12 Oct, overdue 40m in red, 40m ago). The selected row has a detail line under it (todo · added 3h ago · shown 1h ago · acked 5m ago). It refreshes every 10 seconds and after every action. The footer uses the pane's labels (t todo · r reminder · … · p pop top · o pop oldest).

KeyAction
↑ ↓, Home, End, 1–9move the selection (selecting never changes anything)
tadd a todo: type what to remember, Enter adds it (1 credit)
rschedule a reminder: 2h call the bank, the first word is a duration
eedit the selected one's text; it can't be left empty (every 3rd edit costs 1 credit)
wset its due time: a duration (turns a todo into a reminder), or clear to make it a todo again
darchive the selected one (mokkan done); in Archived, reopen it (the footer says reopen there)
a / Aacknowledge the selected one / all
v, Tabgo to the next tab: TODOs → Reminders → Archived. t, r and w leave you where you are; the message says when the item went to another tab (→ Reminders)
p / opop top / pop oldest (mokkan pop / mokkan dequeue), after a confirmation that names the reminder: y: pop n: keep
ssync now
bbuy credits (opens Stripe Checkout in your browser; if that fails, run mokkan buy --no-open for the link)
q, Ctrl-Cquit

When the privacy policy has changed, mokkan ui shows its summary and link in place of the list: y accepts it and goes back to the list, n quits, and d leaves the full screen and runs mokkan delete-account.

Due ones on the tab you are looking at count as shown: acknowledge them with a, or their email goes out after the server's grace period. When you are not logged in, mokkan ui opens on a login screen; mokkan register and mokkan logout stay terminal commands. The view needs a real terminal, so it does not work through /mokkan:mokkan. It has no mouse support, measures wide characters and emoji as well as it can, and is untested on Windows.

Notifications

mokkan notify setup brings scheduled reminders to your shell prompt and your desktop, so you see them without Claude Code open.

It shows one kind of reminder: one made with mokkan in (or given a time with edit --in or --at) whose time has passed and that you haven't acknowledged. Plain pushes are never shown. Showing is read-only: it doesn't mark anything delivered or tell the server a session is active, so the email still goes out until you run mokkan ack.

Setup

Run it in a terminal:

npm i -g @vicmpen/mokkan-cli
mokkan notify setup

Setup bakes the paths of node and of mokkan into your shell config and a background agent, so it needs an install that stays where it is: npm i -g @vicmpen/mokkan-cli, or install.sh's ~/.local/bin/mokkan. It refuses to run from npx or from the Claude Code plugin's copy, because those paths change with every update.

Setup looks at your system, prints a plan and asks before each step:

SystemWhat it installs
macOSthe prompt hook, and a launchd agent (~/Library/LaunchAgents/dev.mokkan.notify.plist)
Linux desktop with systemdthe prompt hook, and a user timer (~/.config/systemd/user/mokkan-notify.timer)
Other Linux desktopsthe prompt hook, and an autostart entry (~/.config/autostart/mokkan-notify.desktop) that runs at your next login
No desktop (a server, WSL)the prompt hook only

The agent checks every 60 seconds and pops up a native notification: terminal-notifier or osascript on macOS, notify-send, gdbus or kdialog on Linux. More than three at once become one "4 reminders due". Desktop notifications stay off until you say yes in setup, and setup sends a test notification and asks whether you saw it. If you run setup over SSH on a machine that has a desktop, the notifications appear on that machine's screen.

The prompt hook works in zsh, bash (including macOS's bash 3.2) and fish; setup installs it for your login shell ($SHELL). It adds a marked block (# >>> mokkan notify >>>) to ~/.zshrc or ~/.bashrc (on macOS, ~/.bash_profile when you have one), with a backup, and for fish it writes ~/.config/fish/conf.d/mokkan.fish. Every open shell prints the reminders once at its next prompt, and again only when the set changes: a new one fires, or you acknowledge one. The hook starts mokkan in the background at most once a minute; the other prompts read a small file.

Setup is safe to run again. Run it again after you change interval, so the agent picks it up.

macOS

Notifications sent through osascript are attributed to Script Editor, and macOS may block them without saying so. If the test notification doesn't appear, allow notifications for Script Editor in System Settings → Notifications, or install terminal-notifier (brew install terminal-notifier), which mokkan prefers when it is there.

Over SSH

On a remote machine the prompt hook prints the reminders in your terminal. It can also send a terminal escape (OSC) that makes the terminal on your own computer show a desktop notification. This is off by default: turn it on when setup asks (it asks only over SSH), or with mokkan notify on osc. The escape is sent only when SSH_CONNECTION is set.

TerminalEscape
iTerm2, WezTerm, GhosttyOSC 9
foot; rxvt-unicode with its notify extensionOSC 777
kittyOSC 99

osc is auto when you turn it on: kitty gets 99, foot 777, everything else 9. SSH usually doesn't pass TERM_PROGRAM on, so over SSH auto mostly means OSC 9. If your terminal needs another one, set osc to "777" or "99" in the config. Terminals that don't know the escape ignore it. Inside tmux, the escape needs set -g allow-passthrough on in ~/.tmux.conf.

Settings

The settings are in ~/.config/mokkan/config.json, created by setup, on or off:

{
  "notifications": {
    "shell": true,
    "desktop": false,
    "osc": "off",
    "interval": 60
  }
}
  • shell: print reminders at the prompt (default on).
  • desktop: native notifications (default off until you say yes in setup).
  • osc: "off", "auto", "9", "777" or "99" (default off).
  • interval: seconds between checks, at least 30 (default 60). Run mokkan notify setup again after changing it, so the background agent uses it too.

mokkan notify off turns every channel off and mokkan notify on turns them on; mokkan notify off desktop turns off one. Neither installs or removes anything. MOKKAN_NOTIFY=0 in the environment turns everything off for that shell or session. If the file can't be read, everything stays off until you fix it, and mokkan notify status says why.

Checking and removing

mokkan notify status     # settings, what is installed, the last check and its result
mokkan notify test       # a test notification through every channel that is on
mokkan notify doctor     # status plus what detection found, to paste into a bug report
mokkan notify remove     # in a terminal: take it all out again

doctor replaces your user name, host name and home directory with placeholders. remove takes out the rc block (after a backup), the fish file, the agent and the files in ~/.config/mokkan/notify/. It keeps your settings in config.json, and leaves alone any file that isn't marked as mokkan's. Open shells keep the hook until you restart them.

If you manage your dotfiles yourself, mokkan shell init zsh (or bash, fish) prints the hook; source it from your own config instead of letting setup edit it.

mokkan logout, an expired session and mokkan delete-account delete the reminder text kept in ~/.config/mokkan/notify/. The hook itself stays and starts showing reminders again after you log back in.

Credits and pricing

mokkan uses prepaid credits. €5 buys 500 credits (1 credit = 1 cent). A new account starts with 50 free credits, and credits never expire.

ActionCost
push1 credit
edit1 credit per 3 edits (every 3rd edit is charged)
Scheduled reminder email1 credit, charged only when the email is actually sent

| pop, dequeue,

Source 2 files
hooks/pane.tsx 989 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer } from 'claude-code'
3
4import type { MokkanMessage, MokkanMode, MokkanPolicy, MokkanReminder, MokkanTab, MokkanView } from '../types'
5
6const PANE = 'mokkan'
7const COLUMNS = 44
8const REFRESH_MS = 15_000
9/** The longest wait between polls: a failed one doubles the wait from REFRESH_MS up to this, a good one resets it. */
10const BACKOFF_MS = 60_000
11/** The stored list is rewritten when it changes, and at least this often, so its `synced` time is never far off. */
12const STORE_MS = 10 * 60_000
13const MESSAGE_MS = 15_000
14const EMPTY: MokkanView = { reminders: [], done: [], balance: null, failure: null, fetchedAt: null }
15const NORMAL: MokkanMode = { kind: 'normal' }
16const view = atom({ plugin: 'mokkan', key: 'view' } as const, EMPTY)
17const mode = atom({ plugin: 'mokkan', key: 'mode' } as const, NORMAL)
18const selected = atom({ plugin: 'mokkan', key: 'selected' } as const, null as string | null)
19const tab = atom({ plugin: 'mokkan', key: 'tab' } as const, 'todos' as MokkanTab)
20const message = atom({ plugin: 'mokkan', key: 'message' } as const, null as MokkanMessage)
21const busy = atom({ plugin: 'mokkan', key: 'busy' } as const, null as string | null)
22const syncing = atom({ plugin: 'mokkan', key: 'syncing' } as const, false)
23const help = atom({ plugin: 'mokkan', key: 'help' } as const, false)
24const privacy = atom({ plugin: 'mokkan', key: 'privacy' } as const, null as MokkanPolicy | null)
25/** The states pop and dequeue take from (`mokkan list` without `--all`): never a scheduled one. */
26const ACTIVE = new Set<MokkanReminder['state']>(['due', 'delivered', 'acknowledged'])
27/** Pale green: the pane's own border while it holds the keys (the engine's frame takes no colour from a plugin). */
28const FOCUS_BORDER = '#a8d8a8'
29const DURATION = /^(?=\d)(?:\d+d)?(?:\d+h)?(?:\d+m)?(?:\d+s)?$/
30/** The tabs in `v` order, with their labels. */
31const TABS: [MokkanTab, string][] = [['todos', 'TODOs'], ['reminders', 'Reminders'], ['archived', 'Archived']]
32const label = (t: MokkanTab) => TABS.find(([k]) => k === t)![1]
33/** The tab `v` goes to next. */
34const after = (t: MokkanTab) => TABS[(TABS.findIndex(([k]) => k === t) + 1) % TABS.length]![0]
35/** A tab's rows: a todo has no due time, a reminder has one; Archived is `mokkan done`. */
36const rowsOf = (v: MokkanView, t: MokkanTab) =>
37  t === 'archived' ? v.done : v.reminders.filter(r => (r.due_at === null) === (t === 'todos'))
38/** A reminder whose time has come and that nobody has acked yet. */
39const isDue = (r: MokkanReminder, now: number) => r.due_at !== null && r.state !== 'acknowledged' && Date.parse(r.due_at) <= now
40
41/** The newest refresh; an older one's result is dropped. */
42let seq = 0
43/** True while a CLI action runs: every key waits for it. */
44let running = false
45/** The id of the last message said. */
46let said = 0
47/** The digit just typed while rows 10+ exist, so a second one within a second makes a two-digit row: 1 then 2 is row 12. */
48let pending: { digit: number; at: number } | null = null
49/** True from the pane's opening to its first good list, which picks the tab it opens on. */
50let landing = false
51/** True from the pane's opening (or a hot reload that finds it open) to its closing: the poll runs, and a key can leak. */
52let shown = false
53/** The poll's next refresh, armed when the one before lands: one at a time, never overlapping. */
54let poll: Timer | null = null
55/** How long the next poll waits: REFRESH_MS, doubled after each failed refresh up to BACKOFF_MS. */
56let wait = REFRESH_MS
57/** When this module last wrote the list to `$.store`. */
58let storedAt = 0
59/** The CLI's argv, looked up once per load of this module. */
60let resolved: Promise<string[]> | null = null
61/** Whether the pane held the keys at its last draw, and when a draw last saw it let them go: a key no Button binds leaves the pane and reaches the prompt around that redraw, just before or just after it. */
62let heldKeys = false
63let lostAt = 0
64/** A key this soon after the pane lost the keys is one that leaked; typing after Esc comes later. */
65const LEAK_MS = 100
66
67/** The CLI: this plugin's own bundle, then a dev checkout next to it, then `mokkan` on PATH. */
68function cli($: EngineInterface): Promise<string[]> {
69  return (resolved ??= find($))
70}
71
72async function find($: EngineInterface): Promise<string[]> {
73  const root = $.plugin.root
74  for (const path of [`${root}/scripts/mokkan.mjs`, `${root}/../dist/cli.js`]) {
75    try {
76      await $.fs.stat(path)
77      return ['node', path]
78    } catch {}
79  }
80  return ['mokkan']
81}
82
83/** Exit code 4: the account must accept an updated privacy policy before the server does anything more for it. */
84const PRIVACY_REQUIRED = 4
85
86/**
87 * `code` is the CLI's exit code: 1 a user error (logged out included), 2 the server or network, 4 the privacy policy to
88 * accept; null when it never ran. A 4 shows the acceptance view; registration, having no account yet, handles its own.
89 */
90async function run($: EngineInterface, args: string[], env?: Record<string, string>): Promise<{ ok: boolean; code: number | null; out: string }> {
91  let r: { ok: boolean; code: number | null; out: string }
92  try {
93    const { exitCode, stdout, stderr } = await $.process.run([...(await cli($)), ...args, '--json'], { timeoutMs: 15_000, env })
94    r = { ok: exitCode === 0, code: exitCode, out: exitCode === 0 ? stdout : (stderr || stdout).trim() }
95  } catch (err) {
96    return { ok: false, code: null, out: err instanceof Error ? err.message : String(err) }
97  }
98  if (r.code === PRIVACY_REQUIRED && args[0] !== 'register') await gate($)
99  return r
100}
101
102/** `mokkan privacy --json`: needs no login; null, said on the status line, when it fails. */
103async function policy($: EngineInterface): Promise<MokkanPolicy | null> {
104  const r = await run($, ['privacy'])
105  const p = r.ok ? json<MokkanPolicy>(r.out) : null
106  if (typeof p?.version === 'string' && typeof p.url === 'string' && Array.isArray(p.summary)) return p
107  await say($, firstLine(r.out) || 'could not fetch the privacy policy', 'error')
108  return null
109}
110
111/** The acceptance view in place of the list, with the policy as it is now; whatever was being typed or asked is dropped. */
112async function gate($: EngineInterface): Promise<void> {
113  const p = await policy($)
114  if (!p) return
115  await update($, privacy, () => p)
116  await update($, mode, () => NORMAL)
117  await update($, help, () => false)
118}
119
120/** `/mokkan <words>`: the CLI's own text, as the slash command shows it (`--exit-zero` puts its errors on stdout too). */
121async function runLine($: EngineInterface, line: string): Promise<string> {
122  try {
123    const { stdout } = await $.process.run([...(await cli($)), '--argline', line, '--exit-zero'], { timeoutMs: 15_000 })
124    return stdout.trim() || 'No output from mokkan.'
125  } catch (err) {
126    return `mokkan failed: ${err instanceof Error ? err.message : String(err)}`
127  }
128}
129
130/** Verbs that need a terminal of their own: `/mokkan` says where to run them instead. */
131const TERMINAL_ONLY: Record<string, string> = {
132  ui: 'mokkan ui is a full-screen view: run it in a terminal. Here, /mokkan alone opens the pane.',
133  watch: 'mokkan watch runs until stopped: run it in a terminal.',
134  login: 'Log in from the pane (/mokkan, then l), or run mokkan login in a terminal.',
135  register: 'Register from the pane (/mokkan, then r), or run mokkan register in a terminal.',
136}
137
138const firstLine = (out: string) => out.split('\n')[0] ?? ''
139/**
140 * Reminder text for `$.ui.notify`, whose channels are terminal escapes: line breaks become spaces, and no control
141 * character or bidi override survives (the rule of the CLI's `src/notify/sanitize.ts`), clamped to 300 code points.
142 */
143const plain = (text: string) => {
144  const clean = text.replace(/[\t\n\v\f\r\x85\u2028\u2029]+/g, ' ').replace(/[\x00-\x1f\x7f-\x9f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, '').replace(/\s+/g, ' ').trim()
145  const points = Array.from(clean)
146  return points.length <= 300 ? clean : `${points.slice(0, 300).join('').trimEnd()}…`
147}
148const json = <T,>(out: string): T | null => {
149  try {
150    return JSON.parse(out) as T
151  } catch {
152    return null
153  }
154}
155const pick = (r: MokkanReminder): MokkanReminder => ({
156  id: r.id, text: r.text, state: r.state, due_at: r.due_at,
157  created_at: r.created_at, delivered_at: r.delivered_at ?? null, acknowledged_at: r.acknowledged_at ?? null, done_at: r.done_at ?? null,
158})
159
160async function refresh($: EngineInterface): Promise<void> {
161  const mine = ++seq
162  // This refresh stands for the poll's next one: the poll is armed again when it lands.
163  poll?.cancel()
164  poll = null
165  let failed = true
166  await update($, syncing, () => true)
167  try {
168    // One process for the whole look: the list, the history, the balance and a heartbeat (which makes an open pane
169    // an active session: the server then waits for it to show what comes due), and delivering what is due.
170    const sync = await run($, ['sync', '--source', 'claude-code-pane', '--deliver'])
171    if (mine !== seq) return
172    const got = sync.ok ? json<{ reminders: MokkanReminder[]; done: MokkanReminder[] | null; balance: number | null; delivered: string[] | null }>(sync.out) : null
173    // The policy to accept (run showed it): the account and its list stand, so the cached list stays for after.
174    if (sync.code === PRIVACY_REQUIRED) return
175    failed = !got
176    const before = await read($, view)
177    let next: MokkanView = got
178      ? {
179          reminders: got.reminders.map(pick),
180          done: got.done?.map(pick) ?? before.done,
181          balance: got.balance ?? before.balance,
182          failure: null,
183          fetchedAt: await $.clock.now(),
184        }
185      : sync.code === 1 // a user error on a bare sync: not logged in, or the session expired
186        ? { ...EMPTY, failure: { kind: 'loggedOut', text: firstLine(sync.out) } }
187        : { ...before, failure: { kind: 'offline', text: firstLine(sync.out) || 'mokkan failed' } }
188    // A timed reminder that is due has been shown nowhere: toast it, and sync marked it delivered, so the server emails
189    // it only if it isn't acked within its grace period. A todo is due the moment it is pushed: never.
190    if (got) {
191      for (const r of next.reminders) {
192        if (r.due_at === null || r.state !== 'due') continue
193        $.ui.toast(`mokkan: due · ${r.text}`, { timeoutMs: MESSAGE_MS })
194        void notify($, r.text)
195      }
196      const delivered = got.delivered ?? []
197      if (delivered.length > 0) {
198        const at = new Date(await $.clock.now()).toISOString()
199        next = { ...next, reminders: next.reminders.map(r => (delivered.includes(r.id) ? { ...r, state: 'delivered', delivered_at: at } : r)) }
200      }
201    }
202    await update($, view, () => next)
203    if (got || next.failure?.kind === 'loggedOut') await update($, privacy, () => null)
204    // The last good list paints the pane at once the next time it opens, in this session or another: written when it
205    // changed, or now and then for its `synced` time, not at every poll.
206    const now = await $.clock.now()
207    if (got && (!sameList(before, next) || now - storedAt >= STORE_MS)) {
208      await $.store.set('view', next)
209      storedAt = now
210    } else if (next.failure?.kind === 'loggedOut') await $.store.delete('view')
211    // It opens on Reminders while one is due, else on TODOs.
212    if (got && landing) {
213      landing = false
214      await land($, next)
215    }
216    // A row that left the tab (archived, reopened, or moved by w) takes the selection with it.
217    const [sel, tb] = await Promise.all([read($, selected), read($, tab)])
218    if (sel !== null && !rowsOf(next, tb).some(r => r.id === sel)) await update($, selected, () => null)
219  } finally {
220    if (mine === seq) {
221      wait = failed ? Math.min(wait * 2, BACKOFF_MS) : REFRESH_MS
222      arm($)
223      await update($, syncing, () => false)
224    }
225  }
226}
227
228/** The list, the history and the balance alike: what the pane shows of a sync, its time aside. */
229const sameList = (a: MokkanView, b: MokkanView) =>
230  a.balance === b.balance && JSON.stringify([a.reminders, a.done]) === JSON.stringify([b.reminders, b.done])
231
232/**
233 * A native notification through the user's own notification channel (Claude Code 2.1.295+), which reaches a terminal
234 * behind another window. Best effort: with no channel it resolves `isSent: false`, and on an older build, which has no
235 * `ui.notify`, the call throws; the toast has shown it either way.
236 */
237async function notify($: EngineInterface, text: string): Promise<void> {
238  try {
239    await $.ui.notify(plain(text), { title: 'mokkan: due' })
240  } catch {}
241}
242
243async function land($: EngineInterface, v: MokkanView): Promise<void> {
244  const now = await $.clock.now()
245  await update($, tab, () => (v.reminders.some(r => isDue(r, now)) ? 'reminders' : 'todos'))
246}
247
248/** Before the first look of this session: the last good list from `$.store`, which every session shares. */
249async function paintCached($: EngineInterface): Promise<void> {
250  const v = await read($, view)
251  if (v.fetchedAt !== null || v.failure !== null) return
252  const cached = (await $.store.get('view')) as MokkanView | undefined
253  if (!Array.isArray(cached?.reminders) || !Array.isArray(cached.done)) return
254  await update($, view, () => cached)
255  landing = false
256  await land($, cached)
257}
258
259/** Refreshes `wait` after the last refresh lands, while the pane is open; `ui.close` stops it. */
260function startPoll($: EngineInterface): void {
261  shown = true
262  if (!poll) arm($)
263}
264
265function arm($: EngineInterface): void {
266  poll?.cancel()
267  poll = shown ? $.clock.after(wait, () => { poll = null; void refresh($) }) : null
268}
269
270function stopPoll(): void {
271  shown = false
272  poll?.cancel()
273  poll = null
274  wait = REFRESH_MS
275}
276
277async function say($: EngineInterface, text: string, tone: NonNullable<MokkanMessage>['tone'] = 'ok'): Promise<void> {
278  const id = ++said
279  await update($, message, (): MokkanMessage => ({ text: tone === 'error' ? `error: ${text}` : text, tone, id }))
280  $.clock.after(MESSAGE_MS, () => update($, message, m => (m?.id === id ? null : m)))
281}
282
283/** Runs one CLI call at a time: the header shows `verb` until it returns, and keys pressed meanwhile are dropped. */
284async function work<T>($: EngineInterface, verb: string, f: () => Promise<T>): Promise<T | undefined> {
285  if (running) return undefined
286  running = true
287  try {
288    await update($, busy, () => verb)
289    return await f()
290  } finally {
291    running = false
292    await update($, busy, () => null)
293  }
294}
295
296/** Runs a mutating command, reports on the status line, and refreshes the pane; true when it worked. */
297async function act($: EngineInterface, verb: string, args: string[], done: string, first?: () => Promise<unknown>): Promise<boolean> {
298  const ok = await work($, verb, async () => {
299    await first?.()
300    const r = await run($, args)
301    // A 4 has shown the acceptance view, which says it all; a refresh would only ask again.
302    if (r.code === PRIVACY_REQUIRED) return null
303    await say($, r.ok ? done : firstLine(r.out) || 'failed', r.ok ? 'ok' : 'error')
304    return r.ok
305  })
306  if (ok !== undefined && ok !== null) void refresh($)
307  return ok === true
308}
309
310async function open($: EngineInterface, asked: boolean): Promise<void> {
311  await $.ui.open(asked ? { id: PANE, title: 'mokkan', columns: COLUMNS, focus: true } : { id: PANE, title: 'mokkan', columns: COLUMNS })
312  landing = true
313  await paintCached($)
314  startPoll($)
315  void refresh($)
316}
317
318const reveal = ($: EngineInterface, id: string) => $.ui.scroll({ in: PANE, to: { key: `row-${id}` } }).catch(() => {})
319
320
321/** Display width: wide and emoji graphemes take 2 cells, East-Asian-ambiguous ones 1. */
322const JOINS = /[\p{M}\u200D\uFE00-\uFE0F\u{1F3FB}-\u{1F3FF}\u{E0020}-\u{E007F}]/u
323const FLAG = /\p{Regional_Indicator}/u
324function graphemes(text: string): string[] {
325  const out: string[] = []
326  for (const ch of text) {
327    const last = out[out.length - 1]
328    if (last !== undefined && (JOINS.test(ch) || last.endsWith('\u200D') || (FLAG.test(ch) && FLAG.test(last) && [...last].length === 1))) out[out.length - 1] = last + ch
329    else out.push(ch)
330  }
331  return out
332}
333function cells(g: string): number {
334  if (/\p{Emoji_Presentation}|\uFE0F|\p{Regional_Indicator}/u.test(g)) return 2
335  const c = g.codePointAt(0) ?? 0
336  const wide = (c >= 0x1100 && c <= 0x115f) || (c >= 0x2e80 && c <= 0xa4cf && c !== 0x303f) || (c >= 0xac00 && c <= 0xd7a3)
337    || (c >= 0xf900 && c <= 0xfaff) || (c >= 0xfe30 && c <= 0xfe4f) || (c >= 0xff00 && c <= 0xff60) || (c >= 0xffe0 && c <= 0xffe6) || (c >= 0x20000 && c <= 0x3fffd)
338  return wide ? 2 : 1
339}
340function fit(text: string, width: number): string {
341  const gs = graphemes(text)
342  if (gs.reduce((n, g) => n + cells(g), 0) <= width) return text
343  let out = ''
344  let used = 0
345  for (const g of gs) {
346    if (used + cells(g) > width - 1) break
347    out += g
348    used += cells(g)
349  }
350  return `${out}…`
351}
352/** Wraps to `first` cells on the first line and `rest` on the others, at the last space; a word wider than its line is cut. */
353function wrap(text: string, first: number, rest: number): string[] {
354  const lines: string[] = []
355  let line: string[] = []
356  let used = 0
357  for (const g of graphemes(text)) {
358    if (used + cells(g) > (lines.length === 0 ? first : rest) && line.length > 0) {
359      const space = g === ' ' ? line.length : line.lastIndexOf(' ')
360      const carried = space > 0 ? line.splice(space).slice(1) : []
361      lines.push(line.join(''))
362      line = carried
363      used = carried.reduce((n, c) => n + cells(c), 0)
364      if (g === ' ') continue
365    }
366    line.push(g)
367    used += cells(g)
368  }
369  return [...lines, line.join('')]
370}
371
372const span = (ms: number) => {
373  const s = Math.max(0, Math.floor(ms / 1000))
374  return s < 60 ? `${s}s` : s < 3600 ? `${Math.floor(s / 60)}m` : s < 86_400 ? `${Math.floor(s / 3600)}h` : `${Math.floor(s / 86_400)}d`
375}
376const ago = (iso: string | null, now: number) => (iso ? ` ${span(now - Date.parse(iso))} ago` : '')
377const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
378const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
379const hm = (d: Date) => `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
380
381/** The time column, reminders only: when it fires, how overdue it is, or how long ago it was shown. */
382function when(r: MokkanReminder, now: number): string {
383  if (r.due_at === null || r.state === 'done') return ''
384  const at = Date.parse(r.due_at)
385  const d = new Date(at)
386  if (at <= now) return r.state === 'due' || r.state === 'scheduled' ? `overdue ${span(now - at)}` : `${span(now - at)} ago`
387  if (at - now < 3_600_000) return `in ${Math.ceil((at - now) / 60_000)}m`
388  if (d.toDateString() === new Date(now).toDateString()) return hm(d)
389  if (at - now < 7 * 86_400_000) return `${DAYS[d.getDay()]} ${hm(d)}`
390  return `${d.getDate()} ${MONTHS[d.getMonth()]}`
391}
392
393/** The mark's color is the kind (cyan a todo, magenta a reminder); its shape `·` once acked, `✓` once done, a bar before. */
394type Kind = 'cyan' | 'magenta'
395const kind = (r: MokkanReminder): Kind => (r.due_at === null ? 'cyan' : 'magenta')
396const mark = (r: MokkanReminder): [string, boolean] =>
397  r.state === 'done' ? ['✓', true] : r.state === 'acknowledged' ? ['·', true] : ['▎', false]
398
399/** The selected row's history, `todo · added 3h ago · shown 1h ago · acked 5m ago`, in lines of `width` broken between parts. */
400function detail(r: MokkanReminder, now: number, width: number): string[] {
401  const parts = r.state === 'done'
402    ? [`archived${ago(r.done_at, now)}`, `added${ago(r.created_at, now)}`]
403    : [r.due_at === null ? 'todo' : 'reminder', `added${ago(r.created_at, now)}`, r.delivered_at && `shown${ago(r.delivered_at, now)}`, r.acknowledged_at && `acked${ago(r.acknowledged_at, now)}`]
404  const lines: string[] = []
405  for (const part of parts.filter((x): x is string => Boolean(x))) {
406    const last = lines[lines.length - 1]
407    if (last !== undefined && [...`${last} · ${part}`].length <= width) lines[lines.length - 1] = `${last} · ${part}`
408    else lines.push(part)
409  }
410  return lines
411}
412
413const FIELD: Record<Extract<MokkanMode, { kind: 'input' }>['purpose'], { label: string; hint: string; submit: string }> = {
414  push: { label: 'new todo', hint: 'what to remember · 1 credit', submit: 'add' },
415  in: { label: 'new reminder', hint: '2h call the bank · 1 credit, +1 held for the email', submit: 'schedule' },
416  edit: { label: 'edit', hint: 'new text · every 3rd edit costs 1 credit', submit: 'save' },
417  time: { label: 'due in', hint: '2h, or clear to make it a todo', submit: 'set' },
418  feedback: { label: 'feedback', hint: 'to the mokkan developer · free · shift+enter for a new line', submit: 'send' },
419}
420
421/** The help view (`h`): what mokkan is, the glyphs, the acts that are easy to mix up, and the costs. */
422const HELP_INTRO = 'A stack of todos and reminders that every Claude Code, Codex and terminal session shares.'
423const HELP_GLYPHS: [string, Kind | 'dim', string][] = [
424  ['▎', 'cyan', 'todo: a note with no time'],
425  ['▎', 'magenta', 'reminder: a note with a due time'],
426  ['·', 'dim', 'acked'],
427  ['✓', 'dim', 'archived'],
428]
429const HELP_TEXT = [
430  'A due reminder nobody acks is emailed to you. Ack (a) says you\'ve seen it: the email stops and it stays on the stack.',
431  'TODOs and Reminders each list their own kind; v cycles the tabs. w moves a row between them: a time makes it a reminder, clear makes it a todo.',
432  'Archive (d) finishes the selected one, as Enter on it does after asking. Finished ones move to Archived, where d reopens them.',
433  '↑↓, Tab or a row\'s number select it: type 1 then 2 for row 12. ctrl+x tab gives the pane the keys; Esc gives them back.',
434  'A todo costs 1 credit. A reminder costs 1, plus 1 held for its email and given back if you ack it first. Every 3rd edit costs 1; the rest is free.',
435  'b opens Stripe Checkout to add credits. In a terminal, mokkan ui opens this full screen.',
436  'f sends feedback to the mokkan developer, free; shift+enter starts a new line.',
437  'To see reminders when Claude Code is closed, at your shell prompt and on your desktop, run npm i -g @vicmpen/mokkan-cli, then mokkan notify setup, in a terminal.',
438  'Privacy policy: mokkan.dev/privacy. To delete your account and everything on it, run mokkan delete-account in a terminal (or npx @vicmpen/mokkan-cli delete-account).',
439]
440/** Under the acceptance view: the pane can't delete an account, so it names the terminal command, both ways (the pane's own CLI is never the one on PATH). */
441const DELETE_INSTEAD = 'delete instead: in a terminal run mokkan delete-account (or npx @vicmpen/mokkan-cli delete-account)'
442
443/** `group`: the key hints start a new line before it, one line per kind of key. */
444type Action = { label: string; hotkey: string; needsField?: true; group?: true; run: () => unknown }
445
446export const register: Register = on => {
447  // The password as typed, in this module alone: never in $.state, never drawn, cleared after each attempt.
448  let secret = ''
449
450  // A hot reload cancels the poll but leaves the pane open: start it again.
451  on('session.start', async ($, e, next) => {
452    if ((await $.ui.panes()).some(p => p.id === PANE)) startPoll($)
453    return next(e)
454  })
455
456  // Closed by /mokkan, by the person or by an unload: nothing polls, and no key is taken for it.
457  on('ui.close', { id: PANE }, ($, e, next) => {
458    stopPoll()
459    heldKeys = false
460    lostAt = 0
461    return next(e)
462  })
463
464  // No session.start follows a /clear, /resume or /branch: an open pane reloads here instead of on the next tick.
465  on('classic.SessionStart', { source: ['clear', 'resume', 'fork'] }, async ($, e, next) => {
466    if ((await $.ui.panes()).some(p => p.id === PANE)) void refresh($)
467    return next(e)
468  })
469
470  // `/mokkan` alone toggles the pane; `/mokkan <verb> …` runs the CLI and shows its output, with no model turn.
471  // The engine keeps the bare `/mokkan` for this plugin's skill, so typing it runs `mokkan:mokkan`: the hook answers that
472  // (and a user-level `/mokkan`, should one exist). Claude still uses the skill when asked in words.
473  on('command.run', { command: ['mokkan:mokkan', 'mokkan'] }, async ($, e) => {
474    const line = e.args.trim()
475    const isOpen = (await $.ui.panes()).some(p => p.id === PANE)
476    if (line) {
477      const verb = line.split(/\s+/)[0]!
478      if (TERMINAL_ONLY[verb]) return { text: TERMINAL_ONLY[verb] }
479      const text = await runLine($, line)
480      if (isOpen) void refresh($)
481      return { text }
482    }
483    if (isOpen) {
484      await $.ui.close({ id: PANE })
485      return { text: 'mokkan pane closed.' }
486    }
487    await open($, true)
488    const { isFullscreen, columns } = e.presentation
489    const where = isFullscreen ? (columns >= 110 ? 'docked beside the transcript' : `inline: the fullscreen layout docks from 110 columns, this terminal is ${columns}`) : 'inline: the main-screen layout never docks a pane'
490    return { text: `mokkan pane opened, ${where}. Esc hands the keys back; ctrl+x tab takes them again. /mokkan again closes it.` }
491  })
492
493  // The engine's focus ring walks the pane (↑/↓, Tab, clicks); a row it lands on becomes the ▸ selection too.
494  on('ui.focus', { requestId: PANE }, async ($, e, next) => {
495    const el = e.element
496    if (el?.startsWith('row-')) {
497      await update($, selected, () => el.slice(4))
498      void reveal($, el.slice(4))
499    }
500    return next(e)
501  })
502
503  // A key no Button binds leaves the pane for the prompt: one typed while the pane held the keys is dropped, and the pane takes them back.
504  // ctrl/cmd combinations and pastes go on; Esc never reaches here.
505  on('prompt.edit', async ($, e, next) => {
506    // Most keys never had the pane hold them: they reach the prompt with no call to the engine.
507    if (!heldKeys && lostAt === 0) return next(e)
508    if (e.key === undefined || e.key.ctrl || e.key.meta || [...e.inputText].length !== 1) return next(e)
509    // `shown` says the pane is open (ui.close clears it) with no call to the engine; only a key just past Esc reads the clock.
510    if (!shown) return next(e)
511    if (!heldKeys && (await $.clock.now()) - lostAt >= LEAK_MS) {
512      // The Esc is over: from here keys go straight to the prompt again.
513      lostAt = 0
514      return next(e)
515    }
516    void $.ui.open({ id: PANE, title: 'mokkan', columns: COLUMNS, focus: true })
517    return { text: e.text, cursor: e.cursor }
518  })
519
520  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
521    if (e.surface === 'terminal') {
522      const holds = e.props.isFocused !== false
523      if (heldKeys && !holds) lostAt = await $.clock.now()
524      heldKeys = holds
525    }
526    const t = $.ui.resolve(e)
527    const { Box, Text, Button } = t
528    const Input = e.surface !== 'mobile' && 'Input' in t ? t.Input : null // mobile has no Input
529    const [v, m, sel, tb, msg, verb, sync, helping, gated, now] = await Promise.all([
530      read($, view), read($, mode), read($, selected), read($, tab), read($, message), read($, busy), read($, syncing), read($, help), read($, privacy), $.clock.now(),
531    ])
532    // The terminal gets the pane's own border, two columns of the body; the remote surfaces draw their own focus.
533    const framed = e.surface === 'terminal'
534    const width = (e.props.bodyColumns ?? e.viewport?.columns ?? COLUMNS) - (framed ? 2 : 0)
535    const docked = e.props.placement === 'dock'
536    const bodyRows = e.props.scroll?.bodyRows ?? e.viewport?.rows ?? 24
537    const focused = e.surface !== 'terminal' || e.props.isFocused !== false
538    const loggedOut = v.failure?.kind === 'loggedOut'
539    const offline = v.failure?.kind === 'offline'
540    const list = rowsOf(v, tb)
541    const current = list.find(r => r.id === sel)
542
543    /** Every key goes through here: dropped while a CLI call runs; it clears the message said before it. */
544    const go = <A extends unknown[]>(f: (...a: A) => unknown) => (...a: A) => {
545      if (running) return
546      const before = said
547      void update($, message, was => (was && was.id <= before ? null : was))
548      return f(...a)
549    }
550    const needOne = () => say($, 'select a row first (its number or ↑↓)', 'note')
551    const cancel = () => { secret = ''; return update($, mode, () => NORMAL) }
552    const switchView = async (to?: MokkanTab) => {
553      await update($, tab, was => to ?? after(was))
554      await update($, selected, () => null)
555    }
556    // The ring follows a click or a digit too, so ↑/↓ and ←/→ walk on from the selected row.
557    const select = async (r: MokkanReminder) => {
558      await update($, selected, () => r.id)
559      void reveal($, r.id)
560      void $.ui.focus({ requestId: PANE, key: `row-${r.id}` }).catch(() => {})
561    }
562    const askDone = (r: MokkanReminder) =>
563      update($, mode, (): MokkanMode => ({ kind: 'confirm', action: r.state === 'done' ? 'undone' : 'done', target: r.text, targetId: r.id }))
564    /** A press on the row already selected (Enter under the focus, a click, its digit) asks to finish it, or reopen it. */
565    const press = (r: MokkanReminder) => (r.id === sel ? askDone(r) : select(r))
566    /** A digit key selects its row at once; within a second of the one before, the two make rows 10–99. */
567    const typed = async (d: number) => {
568      const at = await $.clock.now()
569      const was = pending
570      pending = null
571      const two = was && at - was.at < 1000 ? list[was.digit * 10 + d - 1] : undefined
572      if (two) return select(two)
573      if (d === 0) return say($, 'type 1 then 0 for row 10', 'note')
574      const r = list[d - 1]
575      if (!r) return
576      if (list.length < d * 10) return press(r)
577      const mine = pending = { digit: d, at }
578      // The selected row's own digit asks only once no second digit follows it.
579      if (r.id === sel) $.clock.after(1000, async () => {
580        if (pending !== mine || running) return
581        pending = null
582        const [still, md] = await Promise.all([read($, selected), read($, mode)])
583        if (still === r.id && md.kind === 'normal') await askDone(r)
584      })
585      return select(r)
586    }
587    const toggleDone = (id: string, text: string, reopen: boolean, first?: () => Promise<unknown>) => reopen
588      ? act($, 'reopening…', ['undone', id], `reopened · ${text}`, first)
589      : act($, 'archiving…', ['done', id], `archived · ${text}`, first)
590    const field = async (purpose: 'push' | 'in' | 'edit' | 'time' | 'feedback') => {
591      const needsOne = purpose === 'edit' || purpose === 'time'
592      if (needsOne && (!current || current.state === 'done')) return needOne()
593      const next: MokkanMode = { kind: 'input', purpose, targetId: current?.id, value: purpose === 'edit' ? current?.text ?? '' : '' }
594      await update($, mode, () => next)
595      void $.ui.focus({ requestId: PANE, key: 'field' }).catch(() => {})
596    }
597    const confirm = async (action: 'pop' | 'dequeue' | 'logout') => {
598      if (action === 'logout') {
599        const r = await work($, 'checking account…', () => run($, ['status']))
600        if (r === undefined) return
601        const email = r.ok ? json<{ me?: { email?: string } }>(r.out)?.me?.email : undefined
602        return update($, mode, (): MokkanMode => ({ kind: 'confirm', action, target: email ?? '' }))
603      }
604      const takes = v.reminders.filter(r => ACTIVE.has(r.state))
605      const target = action === 'pop' ? takes[0] : takes[takes.length - 1]
606      if (!target) return say($, 'the stack is empty', 'note')
607      return update($, mode, (): MokkanMode => ({ kind: 'confirm', action, target: target.text }))
608    }
609    // Registration shows the policy's summary first, as `mokkan register` does in a terminal.
610    const startAuth = async (flow: 'login' | 'register') => {
611      secret = ''
612      const p = flow === 'register' ? await work($, 'fetching the privacy policy…', () => policy($)) : null
613      if (flow === 'register' && !p) return
614      await update($, mode, (): MokkanMode => ({ kind: 'auth', flow, step: p ? 'policy' : 'email', email: '', otp: '', masked: '', policy: p ?? null }))
615      if (!p) void $.ui.focus({ requestId: PANE, key: 'auth' }).catch(() => {})
616    }
617    /** y on the summary: on to the email, or back to the password when a changed policy was shown again after the code. */
618    const continueAuth = async () => {
619      await update($, mode, (was): MokkanMode => (was.kind === 'auth' ? { ...was, step: was.otp ? 'password' : 'email' } : was))
620      void $.ui.focus({ requestId: PANE, key: 'auth' }).catch(() => {})
621    }
622    const accept = async (p: MokkanPolicy) => {
623      const accepted = await work($, 'accepting…', async () => {
624        const r = await run($, ['accept', '--yes', '--version', p.version])
625        // 4: the policy changed while it was shown; run has shown the new one.
626        if (r.code === PRIVACY_REQUIRED) return false
627        if (!r.ok) {
628          await say($, firstLine(r.out) || 'failed', 'error')
629          return false
630        }
631        await update($, privacy, () => null)
632        await say($, 'privacy policy accepted')
633        return true
634      })
635      if (accepted) await refresh($)
636    }
637
638    const toggleHelp = () => update($, help, was => !was)
639    // As `mokkan ui`'s b: the CLI opens the checkout itself, and only a Stripe address.
640    const buy = () => work($, 'opening checkout…', async () => {
641      const r = await run($, ['buy'])
642      if (r.code === PRIVACY_REQUIRED) return
643      if (!r.ok) return say($, firstLine(r.out) || 'failed', 'error')
644      await say($, json<{ opened?: boolean }>(r.out)?.opened === true
645        ? 'Opened Stripe Checkout in your browser; the balance updates after payment.'
646        : 'Could not open a browser here. Run: mokkan buy --no-open (prints the link).')
647    })
648    const keys: Record<string, Action> = gated
649      ? {
650          accept: { label: 'accept', hotkey: 'y', run: () => accept(gated) },
651          close: { label: 'close', hotkey: 'n', run: () => $.ui.close({ id: PANE }) },
652        }
653      : helping
654      ? {
655          help: { label: 'back', hotkey: 'h', run: toggleHelp },
656          close: { label: 'close', hotkey: 'q', run: () => $.ui.close({ id: PANE }) },
657        }
658      : loggedOut
659      ? {
660          login: { label: 'log in', hotkey: 'l', needsField: true, run: () => startAuth('login') },
661          register: { label: 'register', hotkey: 'r', needsField: true, run: () => startAuth('register') },
662          refresh: { label: 'sync', hotkey: 's', run: () => refresh($) },
663          help: { label: 'help', hotkey: 'h', run: toggleHelp },
664          close: { label: 'close', hotkey: 'q', run: () => $.ui.close({ id: PANE }) },
665        }
666      // Each key is its label's first letter; a line per kind: add, the selected row, the stack, the rest.
667      : {
668          push: { label: 'todo', hotkey: 't', needsField: true, run: () => field('push') },
669          in: { label: 'reminder', hotkey: 'r', needsField: true, run: () => field('in') },
670          edit: { label: 'edit', hotkey: 'e', needsField: true, group: true, run: () => field('edit') },
671          time: { label: 'when', hotkey: 'w', needsField: true, run: () => field('time') },
672          done: { label: tb === 'archived' ? 'reopen' : 'archive', hotkey: 'd', run: () => (current ? toggleDone(current.id, current.text, current.state === 'done') : needOne()) },
673          ack: { label: 'ack', hotkey: 'a', run: () => (current && current.state !== 'done' ? act($, 'acking…', ['ack', current.id], `acked · ${current.text}`) : needOne()) },
674          // Pop and dequeue are off for now.
675          // pop: { label: 'pop top', hotkey: 'p', group: true, run: () => confirm('pop') },
676          // dequeue: { label: 'pop oldest', hotkey: 'o', run: () => confirm('dequeue') },
677          view: { label: `view ${label(after(tb)).toLowerCase()}`, hotkey: 'v', group: true, run: () => switchView() },
678          refresh: { label: 'sync', hotkey: 's', run: () => refresh($) },
679          // The checkout opens on the machine running Claude Code: of no use to someone on a phone.
680          ...(e.surface !== 'mobile' ? { buy: { label: 'buy', hotkey: 'b', run: () => buy() } } : {}),
681          logout: { label: 'log out', hotkey: 'l', run: () => confirm('logout') },
682          ...(list.length >= 10 ? { zero: { label: '10, 20…', hotkey: '0', run: () => typed(0) } } : {}),
683          feedback: { label: 'feedback', hotkey: 'f', needsField: true, run: () => field('feedback') },
684          help: { label: 'help', hotkey: 'h', run: toggleHelp },
685          close: { label: 'close', hotkey: 'q', run: () => $.ui.close({ id: PANE }) },
686        }
687    /** The key hints as `mokkan ui` draws its footer: `t: todo · r: reminder · …`, a line per group, wrapped to the width. */
688    const hints = () => {
689      const offered = Object.entries(keys).filter(([, a]) => !a.needsField || Input)
690      const lines: [string, Action][][] = [[]]
691      let used = 0
692      for (const entry of offered) {
693        const w = entry[1].hotkey.length + 2 + entry[1].label.length
694        if (used > 0 && (entry[1].group || used + 3 + w > width - 1)) { lines.push([]); used = 0 }
695        used += (used > 0 ? 3 : 0) + w
696        lines[lines.length - 1]!.push(entry)
697      }
698      return (
699        <Box key="legend" flexDirection="column">
700          {lines.map((line, i) => (
701            <Box key={`legend-${i}`}>
702              <Text> </Text>
703              {line.map(([key, a], j) => (
704                <Box key={`cell-${key}`}>
705                  {j > 0 && <Text dimColor> · </Text>}
706                  <Button key={key} hotkey={a.hotkey} plain role={key === 'close' ? 'dismiss' : undefined} onPress={go(() => a.run())}>{a.label}</Button>
707                </Box>
708              ))}
709            </Box>
710          ))}
711        </Box>
712      )
713    }
714
715    const typedSecret = (shown: string) => {
716      // The field shows bullets for what is kept; an edit is taken only at the tail (typing, pasting, backspace).
717      const had = [...secret]
718      const got = [...shown]
719      const n = Math.min(had.length, got.length)
720      const tail = got.slice(n)
721      if (!got.slice(0, n).every((c, i) => c === '•' || c === had[i]) || tail.includes('•')) {
722        secret = ''
723        void say($, 'editing inside the password erased it; type it again', 'error')
724      } else secret = had.slice(0, n).join('') + tail.join('')
725      const masked = '•'.repeat([...secret].length)
726      return update($, mode, was => (was.kind === 'auth' ? { ...was, masked } : was))
727    }
728    /** The policy changed during registration: its new summary, then on with what was typed (the code stands). */
729    const showAgain = async (was: Extract<MokkanMode, { kind: 'auth' }>) => {
730      const p = await work($, 'fetching the privacy policy…', () => policy($))
731      if (!p) return update($, mode, () => was)
732      await update($, mode, (): MokkanMode => ({ ...was, step: 'policy', policy: p }))
733      await say($, 'the privacy policy changed: read it again', 'note')
734    }
735    const authStep = async (raw: string) => {
736      if (m.kind !== 'auth') return
737      const text = raw.trim()
738      if (m.step === 'email') {
739        if (!text) return cancel()
740        if (m.flow === 'login') return update($, mode, (): MokkanMode => ({ ...m, step: 'password', email: text }))
741        const r = await work($, 'sending code…', () => run($, ['register', text, '--start', '--accept-privacy', m.policy?.version ?? '']))
742        if (!r) return
743        if (!r.ok) {
744          await update($, mode, (): MokkanMode => ({ ...m, email: raw }))
745          return say($, firstLine(r.out) || 'could not send the code', 'error')
746        }
747        await say($, `code sent to ${text}`)
748        return update($, mode, (): MokkanMode => ({ ...m, step: 'otp', email: text }))
749      }
750      if (m.step === 'otp') {
751        if (!text) return cancel()
752        return update($, mode, (): MokkanMode => ({ ...m, step: 'password', otp: text }))
753      }
754      const password = secret
755      secret = ''
756      if (!password) return cancel()
757      const retry = () => update($, mode, was => (was.kind === 'auth' ? { ...was, masked: '' } : was))
758      if (m.flow === 'register' && password.length < 10) {
759        await retry()
760        return say($, 'the password needs 10+ characters', 'error')
761      }
762      const r = await work($, m.flow === 'login' ? 'logging in…' : 'registering…', () => m.flow === 'login'
763        ? run($, ['login', m.email], { MOKKAN_PASSWORD: password })
764        : run($, ['register', '--complete', m.email, '--otp', m.otp, '--accept-privacy', m.policy?.version ?? ''], { MOKKAN_PASSWORD: password }))
765      if (!r) return
766      if (r.code === PRIVACY_REQUIRED) return showAgain({ ...m, masked: '' })
767      if (!r.ok) {
768        await retry()
769        return say($, firstLine(r.out) || `${m.flow} failed`, 'error')
770      }
771      await say($, `${m.flow === 'login' ? 'logged in' : 'registered and logged in'} as ${m.email}`)
772      await update($, mode, () => NORMAL)
773      await refresh($)
774    }
775    const submit = async (raw: string) => {
776      if (m.kind !== 'input') return
777      const text = raw.trim()
778      const keep = () => update($, mode, was => (was.kind === 'input' ? { ...was, value: raw } : was))
779      if (!text && m.purpose === 'edit') {
780        await keep()
781        return say($, 'the text can’t be empty', 'error')
782      }
783      if (!text) return cancel()
784      const id = m.targetId ?? ''
785      const was = v.reminders.find(r => r.id === id)
786      const target = was?.text ?? ''
787      const [dur = '', ...rest] = text.split(/\s+/)
788      if (m.purpose === 'in' && (!DURATION.test(dur) || rest.length === 0)) {
789        await keep()
790        return say($, 'start with a duration: 2h call the bank', 'error')
791      }
792      if (m.purpose === 'time' && text !== 'clear' && !DURATION.test(text)) {
793        await keep()
794        return say($, 'type a duration like 2h, or clear', 'error')
795      }
796      // The pane stays on its tab; a row that lands on another one says where it went.
797      const [verbing, args, done]: [string, string[], string] =
798        m.purpose === 'push' ? ['adding…', ['push', text], tb === 'todos' ? `added · ${text}` : `added to TODOs · ${text}`]
799        : m.purpose === 'in' ? ['scheduling…', ['in', dur, rest.join(' ')], `${tb === 'reminders' ? 'scheduled' : 'added to Reminders, due'} in ${dur} · ${rest.join(' ')}`]
800        : m.purpose === 'edit' ? ['saving…', ['edit', id, text], `edited · ${text}`]
801        : m.purpose === 'feedback' ? ['sending…', ['feedback', text], 'feedback sent · thank you']
802        : text === 'clear' ? ['setting due…', ['edit', id, '--clear-due'], `${was?.due_at === null ? 'now a todo' : 'moved to TODOs'} · ${target}`]
803        : ['setting due…', ['edit', id, '--in', text], `${was?.due_at === null ? 'moved to Reminders, due' : 'due'} in ${text} · ${target}`]
804      if (await act($, verbing, args, done)) await update($, mode, () => NORMAL)
805      else await keep()
806    }
807
808    const rule = <Text dimColor>{'─'.repeat(Math.max(1, width))}</Text>
809    // The clock time of the last good fetch, not its age: the pane redraws on changes, not by the second, so an age would go stale.
810    const syncedAt = v.fetchedAt === null ? '' : `synced ${hm(new Date(v.fetchedAt))}`
811    const synced = sync ? 'syncing…' : offline ? `offline${syncedAt && ` · ${syncedAt}`}` : syncedAt || 'loading…'
812    const credits = v.balance === null ? '' : ` · ${v.balance} ${Math.abs(v.balance) === 1 ? 'credit' : 'credits'}`
813    // At 0 the red count says it; a paid command's error then names the fix (`Run: mokkan buy`, or b here).
814    const balance = v.balance === null ? '' : v.balance > 0 && v.balance < 10 ? `${credits} · low` : credits
815    const wide = (text: string) => graphemes(text).reduce((n, g) => n + cells(g), 0)
816
817    return (
818      <Box flexDirection="column" minHeight={docked ? bodyRows : undefined}
819        {...(framed ? { borderStyle: 'round', borderColor: focused ? FOCUS_BORDER : 'gray', borderDimColor: !focused } : {})}>
820        {/* ` mokkan · 42 credits`, the views, a rule; the sync state sits at the bottom, clear of the engine's close mark. */}
821        <Box>
822          <Text bold> mokkan</Text>
823          {!loggedOut && <Text color={v.balance === null || v.balance >= 10 ? undefined : v.balance <= 0 ? 'red' : 'yellow'} dimColor={v.balance === null || v.balance >= 10}>{balance}</Text>}
824        </Box>
825        {helping && <Text bold> Help</Text>}
826        {gated && <Text bold> Privacy policy updated</Text>}
827        {!loggedOut && !helping && !gated && (
828          <Box>
829            <Text> </Text>
830            {TABS.map(([key, name], i) => (
831              <Box key={`view-${key}`}>
832                {i > 0 && <Text dimColor> │ </Text>}
833                <Button key={`tab-${key}`} plain dimColor={key !== tb} onPress={go(() => switchView(key))}>{`${name} ${rowsOf(v, key).length}`}</Button>
834              </Box>
835            ))}
836          </Box>
837        )}
838        {rule}
839        {gated ? (
840          <Box key="privacy" flexDirection="column" paddingLeft={1}>
841            {gated.summary.map((line, i) => <Text key={`summary-${i}`} wrap="wrap">{line}</Text>)}
842            <Text> </Text>
843            <Text wrap="wrap">{gated.url}</Text>
844            <Text> </Text>
845            <Text dimColor wrap="wrap">{DELETE_INSTEAD}</Text>
846          </Box>
847        ) : helping ? (
848          <Box key="help" flexDirection="column" paddingLeft={1}>
849            <Text wrap="wrap">{HELP_INTRO}</Text>
850            <Text> </Text>
851            {HELP_GLYPHS.map(([glyph, tone, label]) => (
852              <Box key={`glyph-${label}`}>
853                <Text color={tone === 'dim' ? undefined : tone} dimColor={tone === 'dim'}>{`${glyph} `}</Text>
854                <Text>{label}</Text>
855              </Box>
856            ))}
857            {HELP_TEXT.map((text, i) => (
858              <Box key={`help-${i}`} flexDirection="column">
859                <Text> </Text>
860                <Text wrap="wrap">{text}</Text>
861              </Box>
862            ))}
863          </Box>
864        ) : loggedOut ? (
865          <Box flexDirection="column">
866            <Text> Not logged in.</Text>
867            {m.kind !== 'auth' && <Text dimColor>{Input ? ' l logs in, r registers.' : ' Log in from a terminal: mokkan login'}</Text>}
868          </Box>
869        ) : (
870          <Box flexDirection="column">
871            {list.length === 0 && (offline && v.fetchedAt === null
872              ? <Text color="red" wrap="truncate">{` ${v.failure?.text ?? ''}`}</Text>
873              : tb === 'archived' ? (
874                <Box flexDirection="column">
875                  <Text dimColor> Nothing archived yet.</Text>
876                  <Text dimColor> d archives the selected row.</Text>
877                </Box>
878              )
879              : (
880                <Box flexDirection="column">
881                  <Text dimColor>{tb === 'todos' ? ' No todos.' : ' No reminders.'}</Text>
882                  {Input && <Text dimColor>{tb === 'todos' ? ' t adds one.' : ' r schedules one.'}</Text>}
883                </Box>
884              ))}
885            {list.map((r, i) => {
886              const n = i + 1
887              // `▸ ▎ 1: ` is 7 cells; with rows 10+ every number takes their width, ` 9: ` above `10: `.
888              const digits = String(list.length).length
889              const lead = 4 + digits + 2
890              const isSel = r.id === sel
891              const time = when(r, now)
892              const [glyph, settled] = mark(r)
893              // `▸ ▎ 1: text`, the time flush right; the selected row has the pointer and bold marks, as in `mokkan ui`.
894              const room = Math.max(4, width - lead - (time ? wide(time) + 2 : 0))
895              // The selected row wraps its whole text under the text column; the others are cut to one line.
896              const [text = '', ...more] = isSel ? wrap(r.text, room, Math.max(4, width - lead)) : [fit(r.text, room)]
897              // No gap when an untimed row's text fills the width: one more cell would wrap the row.
898              const gap = Math.max(time ? 1 : 0, width - lead - wide(text) - wide(time))
899              return (
900                <Box key={r.id} flexDirection="column">
901                  <Box>
902                    <Text bold={isSel}>{isSel ? '▸ ' : '  '}</Text>
903                    <Text bold={isSel} color={kind(r)} dimColor={settled && !isSel}>{`${glyph} `}</Text>
904                    {/* 1–9 are the Button's own hotkeys; 10+ draw their number, typed as two digits. */}
905                    {n <= 9 ? digits > 1 && <Text>{' '.repeat(digits - 1)}</Text> : <Text bold={isSel}>{`${String(n).padStart(digits)}: `}</Text>}
906                    <Button key={`row-${r.id}`} plain hotkey={n <= 9 ? String(n) : undefined} dimColor={(r.state === 'acknowledged' || r.state === 'done') && !isSel} onPress={go(() => (n <= 9 ? typed(n) : press(r)))}>
907                      {text}
908                    </Button>
909                    {gap > 0 && <Text>{' '.repeat(gap)}</Text>}
910                    {time && <Text bold={isSel} color={time.startsWith('overdue') ? 'red' : undefined} dimColor={!time.startsWith('overdue') && !isSel}>{time}</Text>}
911                  </Box>
912                  {more.map((line, j) => <Text key={`more-${j}`}>{`${' '.repeat(lead)}${line}`}</Text>)}
913                  {isSel && detail(r, now, width - lead).map((line, j) => <Text key={`detail-${j}`} dimColor>{`${' '.repeat(lead)}${fit(line, width - lead)}`}</Text>)}
914                </Box>
915              )
916            })}
917          </Box>
918        )}
919
920        {docked && <Box flexGrow={1} />}
921        {/* An error wraps, so the fix at its end (`Run: mokkan buy`) is never cut; the rest stay one line. */}
922        <Box key="status" paddingLeft={1}>
923          <Text color={msg ? { ok: 'green', note: 'yellow', error: 'red' }[msg.tone] : undefined} wrap={msg?.tone === 'error' ? 'wrap' : 'truncate-end'}>{msg?.text ?? ' '}</Text>
924        </Box>
925
926        {m.kind === 'input' && Input && (
927          <Box flexDirection="column" paddingLeft={1}>
928            <Input key="field" autoFocus label={FIELD[m.purpose].label} placeholder={FIELD[m.purpose].hint} value={m.value} submitLabel={FIELD[m.purpose].submit} onSubmit={go(submit)} />
929            <Box gap={1}>
930              <Button key="cancel" plain onPress={go(cancel)}>cancel</Button>
931              <Text dimColor>(Tab to it, then Enter)</Text>
932            </Box>
933          </Box>
934        )}
935        {m.kind === 'auth' && Input && (
936          <Box flexDirection="column" paddingLeft={1}>
937            {m.step === 'policy' && m.policy && (
938              <Box flexDirection="column">
939                {m.policy.summary.map((line, i) => <Text key={`summary-${i}`} wrap="wrap">{line}</Text>)}
940                <Text wrap="wrap">{m.policy.url}</Text>
941                <Box>
942                  <Button key="yes" hotkey="y" plain onPress={go(continueAuth)}>continue</Button>
943                  <Text dimColor> · </Text>
944                  <Button key="no" hotkey="n" plain onPress={go(cancel)}>cancel</Button>
945                </Box>
946              </Box>
947            )}
948            {m.step === 'email' && <Input key="auth" autoFocus label={`${m.flow} email`} placeholder="you@example.com" value={m.email} submitLabel={m.flow === 'login' ? 'next' : 'send code'} onSubmit={go(authStep)} />}
949            {m.step === 'otp' && <Input key="auth" autoFocus label="one-time code" placeholder={`the code emailed to ${m.email}`} value={m.otp} submitLabel="next" onSubmit={go(authStep)} />}
950            {m.step === 'password' && <Input key="auth" autoFocus label={m.flow === 'login' ? `password for ${m.email}` : 'new password (10+ characters)'} placeholder="hidden as you type" value={m.masked} submitLabel={m.flow === 'login' ? 'log in' : 'register'} onInput={typedSecret} onSubmit={go(authStep)} />}
951            {m.step !== 'policy' && (
952              <Box gap={1}>
953                <Button key="cancel" plain onPress={go(cancel)}>cancel</Button>
954                <Text dimColor>(Tab to it, then Enter)</Text>
955              </Box>
956            )}
957          </Box>
958        )}
959        {m.kind === 'confirm' && (
960          <Box flexDirection="column">
961            {/* The question names its target across the width, the answers their outcome below: `y: pop · n: keep`. */}
962            <Text color="yellow">{m.action === 'logout'
963              ? (m.target ? ` log out ${fit(m.target, width - 11)}?` : ' log out of mokkan here?')
964              : m.action === 'done' ? ` archive "${fit(m.target, width - 13)}"?`
965              : m.action === 'undone' ? ` reopen "${fit(m.target, width - 12)}"?`
966              : ` pop "${fit(m.target, width - 9)}"?`}</Text>
967            <Box>
968              <Text> </Text>
969              <Button key="yes" hotkey="y" plain onPress={go(() => m.action === 'logout'
970                ? act($, 'logging out…', ['logout'], 'logged out', () => update($, mode, () => NORMAL))
971                : m.action === 'done' || m.action === 'undone'
972                ? toggleDone(m.targetId ?? '', m.target, m.action === 'undone', () => update($, mode, () => NORMAL))
973                : act($, 'popping…', [m.action], `popped · ${m.target}`, () => update($, mode, () => NORMAL)))}>{m.action === 'logout' ? 'log out' : m.action === 'done' ? 'archive' : m.action === 'undone' ? 'reopen' : 'pop'}</Button>
974              <Text dimColor> · </Text>
975              <Button key="no" hotkey="n" plain onPress={go(() => update($, mode, () => NORMAL))}>{m.action === 'logout' ? 'stay' : 'keep'}</Button>
976            </Box>
977          </Box>
978        )}
979        {m.kind === 'normal' && (focused
980          ? hints()
981          : <Text dimColor> ctrl+x tab to use keys</Text>)}
982        {(verb || !loggedOut) && (
983          <Text key="sync" color={!verb && offline && !sync ? 'yellow' : undefined} dimColor={Boolean(verb) || !offline || sync}>{` ${verb ?? synced}`}</Text>
984        )}
985      </Box>
986    )
987  })
988}
989
types/index.d.ts 66 lines
1export type MokkanReminder = {
2  id: string
3  text: string
4  state: 'scheduled' | 'due' | 'delivered' | 'acknowledged' | 'done'
5  /** Null for a todo (`push`), set for a reminder (`in`, or `t` on a todo). */
6  due_at: string | null
7  created_at: string
8  delivered_at: string | null
9  acknowledged_at: string | null
10  done_at: string | null
11}
12
13export type MokkanView = {
14  /** Every open reminder (`mokkan list --all`), top of the stack first. */
15  reminders: MokkanReminder[]
16  /** Finished reminders (`mokkan done`), newest first. */
17  done: MokkanReminder[]
18  balance: number | null
19  /** Why the last refresh failed: `offline` keeps the last good lists, `loggedOut` clears them. */
20  failure: { kind: 'offline' | 'loggedOut'; text: string } | null
21  /** When the lists were last fetched whole; null until then and after a logout. */
22  fetchedAt: number | null
23}
24
25/** The list shown: the open todos (no due time), the open reminders (a due time), or the finished ones. */
26export type MokkanTab = 'todos' | 'reminders' | 'archived'
27
28/** The last result, drawn on the status line until 15 s pass or the next key: green, yellow for a nudge, red for an error; `id` counts the messages said. */
29export type MokkanMessage = { text: string; tone: 'ok' | 'note' | 'error'; id: number } | null
30
31/** The privacy policy as `mokkan privacy --json` gives it: the version accepted, where the full text is, and its summary lines. */
32export type MokkanPolicy = { version: string; url: string; summary: string[] }
33
34/** What the pane's field is for: a new todo or reminder, or a change to the pointed one. */
35export type MokkanMode =
36  | { kind: 'normal' }
37  | { kind: 'input'; purpose: 'push' | 'in' | 'edit' | 'time' | 'feedback'; targetId?: string; value: string }
38  /** `target` names what the action takes: a reminder's text, or the account; `targetId` the reminder done and undone change. */
39  | { kind: 'confirm'; action: 'pop' | 'dequeue' | 'logout' | 'done' | 'undone'; target: string; targetId?: string }
40  /**
41   * Login or registration: the email, the emailed code (register only), then the password.
42   * `masked` is the bullets drawn for the password; the text itself never enters state.
43   * Registration first shows `policy` (step `policy`), and passes its version to both register steps; null for a login.
44   */
45  | { kind: 'auth'; flow: 'login' | 'register'; step: 'policy' | 'email' | 'otp' | 'password'; email: string; otp: string; masked: string; policy: MokkanPolicy | null }
46
47declare module 'claude-code' {
48  interface PluginState {
49    mokkan: {
50      view: MokkanView
51      mode: MokkanMode
52      selected: string | null
53      tab: MokkanTab
54      message: MokkanMessage
55      /** The verb of the CLI call in flight (`pushing…`), drawn in the header; action keys wait for it. */
56      busy: string | null
57      /** True while a refresh is in flight. */
58      syncing: boolean
59      /** True while the help view (`h`) replaces the list. */
60      help: boolean
61      /** The policy the account must accept (a CLI call exited 4): its acceptance view replaces the list until accepted. */
62      privacy: MokkanPolicy | null
63    }
64  }
65}
66