SLOPSHOPPER

Human in the loop

Claude assigns you the tasks only you can do. They wait in a My tasks pane, counted under the prompt, until you answer or reject them, so nothing Claude needs…

panebandrowsguardcommandtoast
★ 34v0.1.8MITupdated 2026-10-20tzafrir/human-in-the-loop
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · human-in-the-loop
│ ┃ my-tasks ✕ › fix the failing auth test and add an audit log call │ ┃ No tasks for you right now. │ ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /my-tasks │ ⎿ human-in-the-loop: No tasks for you right now. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · my-tasks
No tasks for you right now.
README

Human in the loop: Claude hands you the tasks only you can do; they wait in the My tasks pane until you answer, and your answers go back to Claude

Human in the loop

Claude hands you the tasks only you can do. They wait until you act, and your answer goes back to Claude.

Why

Claude often needs something only you can do: a key in .env, an approval on staging, a command on your own machine, a decision. Today it says so in the middle of a reply. You're busy steering the next fix, and the ask scrolls away. At best Claude keeps repeating "I still need you to…"; at worst the ask is lost.

With this mod, Claude assigns the ask as a task instead. It waits in the My tasks pane, counted under the prompt, until you do it, answer it or reject it.

An example

Get our Stripe webhooks library ready to open-source.

Claude works through it, and three times hits something only you can do: the integration tests need your Stripe key, making the repo public is your call, and the package needs a name. Each becomes a task, and Claude keeps working:

╭─ My tasks ──────────────────────────────────────────────────────────╮
│ ☐ 3 tasks for you                                                   │
│                                                                     │
│ ☐ #1 Add STRIPE_SECRET_KEY to .env  2m                              │
│   The integration tests run against Stripe's test mode and need it. │
│   Done when: It's in .env. Don't paste it here.                     │
│   d: Done   r: Answer…   x: Reject…                                 │
│ ☐ #2 Decide whether to make the repo public  1m                     │
│ ☐ #3 Choose the package's name on npm  now                          │
│                                                                     │
│ Esc: back to the prompt   Hide                                      │
╰─────────────────────────────────────────────────────────────────────╯
☐ 3 tasks for you · /my-tasks
  • #1 you do in your editor, then press d. The key never passes through Claude.
  • #2 is your decision: 1 makes the repo public, 2 keeps it private.
  • #3 needs your words: press r, type @acme/stripe-hooks, Enter.

Answer whenever it suits you. Answers you give while Claude works wait for it, and your next answer after it stops takes them along. Here #1 and #2 were answered while Claude worked and #3 after, so Claude gets them as one message, in your words:

My responses to tasks you gave me (Human in the loop):

#1 Add STRIPE_SECRET_KEY to .env: Done.

#2 Decide whether to make the repo public: I chose "Make it public".

#3 Choose the package's name on npm:
@acme/stripe-hooks

Claude picks up where it left off: the integration tests pass, the repo goes public, and the package gets its name. Publishing is left to you.

How it works

  • Claude assigns with assign_task: an imperative title, why it's needed, what counts as done, and a kind (do, answer or choose).
  • The status line under the prompt counts what's waiting: ☐ 3 tasks for you · /my-tasks.
  • The My tasks pane opens by itself when a task arrives. In fullscreen it's a sidebar beside the transcript; on the main screen it sits above the prompt. /my-tasks opens it any time, with the keyboard.
  • You respond: Done, an option (1–4), an answer (r), or a rejection with a reason (x). Click, or focus the pane with /my-tasks or ctrl+x tab and use the keys.
  • Your answer reaches Claude:
  • while Claude is idle, right away;
  • while it works, it waits, so Claude isn't interrupted, and goes when Claude finishes its turn. If a task is still open then, your answers wait for that one too and arrive together (or with your next prompt). Send now sends right away.
  • Long answers (a log, a stack trace) go through your own prompt box: Long answer… starts it with ↳ Answer to #3:, and you paste and press Enter.
  • Claude keeps working. Unlike a question dialog, a task doesn't stop Claude: it carries on with everything else while the task waits for you, and takes the task back if it finds another way.
  • Nothing is lost across a compaction or a new session: open tasks stay with the project and Claude is told about them again. With several sessions open in one project, each keeps its own tasks, so your answer always reaches the Claude that asked.

It never draws in the band above the prompt, so it works beside band mods such as What's Agent Doing.

Guardrails

  • At most 5 open tasks at a time.
  • The same ask twice is one task.
  • Only the main agent assigns tasks; a subagent reports what it needs in its result.
  • An answer that looks like a secret (an API key, a token, a private key) is held with a warning before it is sent.

Install

In Claude Code:

/plugin marketplace add tzafrir/human-in-the-loop
/plugin install human-in-the-loop@human-in-the-loop

Or from your shell:

claude plugin marketplace add tzafrir/human-in-the-loop
claude plugin install human-in-the-loop@human-in-the-loop

Then start a new session (or run /reload-plugins).

Requirements: Claude Code in a terminal, or in the desktop app's Code tab. The plugin is a mod, written with Claude Code's function hooks, which are early access: they load only where function hooks are enabled, and their API may change between releases.

Data and privacy

  • Stays on your machine. Tasks live in the session's own state and in the plugin's own store (a JSON file under your Claude Code configuration directory), keyed by project folder, so open tasks come back in the next session there. No network, no files of yours, no processes.
  • Your responses become part of the conversation. Claude reads what you answer, and the session's transcript on disk keeps it, like anything you type. That's why tasks ask you to put a secret where it belongs and press Done, never to paste it, and why an answer that looks like a secret is held first.
  • What it adds to the conversation: the three tools, a few lines in the system prompt telling Claude about tasks, your responses, and, at a conversation's start or after a compaction, a short list of the tasks still open.

What the mod puts in the prompts it submits

The mod submits a prompt in two cases, and these are all it puts in one:

  • Your responses to tasks. When you respond to a task while Claude is idle, when Claude finishes a turn with your saved responses waiting and no task left open, or when you press Send now, the mod submits your responses as a prompt in your own words. It opens with "My response to a task you gave me (Human in the loop):" ("My responses to tasks…" for several). Then, for each task, it gives the task's number and the title Claude gave it, and what you did: "Done.", the option you chose, your answer, or "I won't do this." with your reason.
  • One fixed line: "I answered a task while you were finishing your reply; my answer is above." It goes when your answer arrived during Claude's final reply.

Nothing else goes into a prompt it submits. The mod reads two facts about the session, the session's id and its project folder, and puts neither in a prompt. It uses them to keep each session's tasks apart from those of other sessions in the same folder, in the plugin's own store on your machine, and to mark a task an earlier session assigned as "from an earlier session". Nothing else from the conversation, your files or your machine goes in either.

What else it sends to Claude, and which tool calls it answers

  • While Claude works: Send now adds the same response as a row Claude reads at its next step, with a notice in the transcript for you ("Sent your response to #3 to Claude") that Claude doesn't read.
  • Your prompts: the mod reads them only to recognize a long answer (↳ Answer to #3: …), which it turns into that same response, and to attach responses not yet sent as notes Claude reads.
  • The tool calls it answers: only calls to its own three tools, assign_task, list_tasks and withdraw_task, which the mod itself serves. Every other tool call passes through untouched.

Support

Report a problem or ask for a feature in GitHub Issues. Read the privacy policy.

Develop

Load the plugin from a clone; the session reloads it as you edit:

git clone https://github.com/tzafrir/human-in-the-loop
claude --plugin-dir human-in-the-loop
claude plugin validate --strict human-in-the-loop/.claude-plugin/plugin.json
claude plugin test human-in-the-loop
FileWhat it does
hooks/register.tsxThe tools Claude calls, delivering your responses, the My tasks pane and status line, /my-tasks, long answers through the prompt box
hooks/project.tsEach session's tasks in the project's store, and taking on those of sessions that ended
hooks/tasks.tsReading a task from Claude's call, what Claude is told, the status line, secret shapes
hooks/text.tsPrintable labels, ages, sizes
types/index.d.tsThe $.state contract: the tasks, the selection, the open field
tests/register.test.tsxAssigning, the pane and /my-tasks, every response and when it reaches Claude, long answers, tasks carried across sessions
docs/DESIGN.mdThe design and the decisions behind it

License

MIT

Source 6 files
hooks/register.tsx 2126 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, PromptSubmitResult, Register, RenderElement, RenderSurface, StateValue, Timer, ToolSpec } from 'claude-code'
3
4import type { Editing, Task, Took } from '../types'
5import {
6  MAX_OPEN,
7  MAX_TITLE,
8  answerIn,
9  assignedOf,
10  bridgeOf,
11  contextOf,
12  digestOf,
13  isActive,
14  isShown,
15  listOf,
16  looksSecret,
17  messageOf,
18  newsHeadOf,
19  ownHeadOf,
20  parseAsk,
21  sameAsk,
22  statusOf,
23} from './tasks'
24import {
25  ANSWER_LABEL,
26  BUTTON_GAP,
27  HELD,
28  HIDE,
29  MAX_SHOWN_TITLE,
30  REASON_LABEL,
31  REASON_PLACEHOLDER,
32  actionsOf as actionsFor,
33  ageOf,
34  answerButtonsOf,
35  answerPlaceholderOf,
36  doneWhenOf,
37  fieldKeyOf,
38  headlineOf,
39  hintOf,
40  nameOf,
41  placeholderOf,
42  rowsFor,
43  savedOf,
44  selectedOf,
45  sendNowOf,
46  submitLabelOf,
47  titleOf,
48  whyOf,
49} from './pane'
50import type { PaneView } from './pane'
51import {
52  HEARTBEAT_MS,
53  adopt,
54  editedLegacy,
55  elsewhereIn,
56  floorOf,
57  hasLegacyPeer,
58  isEmptyEdit,
59  isSameTask,
60  isSlot,
61  isTakenFrom,
62  keysOf,
63  legacyOf,
64  projectOf,
65  prune,
66  withSlots,
67} from './project'
68import type { Adoption, LegacyEdit, Project, Slot } from './project'
69import { numbersOf, oneLine, printable } from './text'
70
71const PLUGIN = 'human-in-the-loop'
72
73const ASSIGN = 'mcp__human-in-the-loop__assign_task'
74const LIST = 'mcp__human-in-the-loop__list_tasks'
75const WITHDRAW = 'mcp__human-in-the-loop__withdraw_task'
76
77/**
78 * Three lines at the end of the system prompt: where an ask for the user goes
79 * so it stays in front of them, that a review is one even when the reply asks
80 * for it too (the user is often busy and lets the reply's question go by),
81 * and where they see it. Said as what to do,
82 * never what not to: nothing here stops Claude reminding the user of a task.
83 */
84const STEERING = [
85  "When you need something only the user can do (a secret put in place, an action on their machine or an account you can't reach, a decision that's theirs), assign it with mcp__human-in-the-loop__assign_task so it stays in front of them until they act on it.",
86  'That includes asking the user to review or approve your work: assign it as a task even when you also ask in your reply, since they may be busy with other things when you ask, and the task keeps it in front of them.',
87  'The user sees open tasks in their My tasks pane, or opens it with /my-tasks, and their response reaches you as a message.',
88].join('\n')
89
90/** Resolutions pressed this close together go to Claude as one message. */
91const BATCH_MS = 800
92
93/** The longest a person, or Claude, waits on the store: what it doesn't answer by then finishes on its own. */
94const STORE_WAIT_MS = 5000
95
96/** What a tool answers while the session moves to another folder, before it has read that folder's tasks. */
97const MOVING = 'This session is still joining its project: the task store is slow to answer. Try again in a moment.'
98
99/** The pane the tasks wait in, and the command that opens it. */
100const PANE = 'my-tasks'
101const PANE_TITLE = 'My tasks'
102const MAX_PANE_ROWS = 18
103
104/** How a surface draws the pane: its body's width, whether it draws a field and holds the keys, and whether it seats the pane inline. */
105type Seat = Pick<PaneView, 'canType' | 'isFocused'> & { columns: number; isInline: boolean }
106
107/** What goes under the selected task: an open field, across the pane's body, and the buttons, in the task's indent. */
108type Controls = readonly [field: RenderElement | null, buttons: RenderElement | null]
109
110/** An 80-column terminal's main screen: the pane's seat until a surface draws it. */
111const FIRST_SEAT: Seat = { columns: 76, canType: true, isFocused: false, isInline: true }
112
113/** `seats` with `seat` among them: of seats alike but for their width, the narrowest stays, as it takes the most rows. */
114function seatsWith(seats: readonly Seat[], seat: Seat): readonly Seat[] {
115  const alike = seats.find(other => isAlike(other, seat))
116
117  return alike !== undefined && alike.columns <= seat.columns ? seats : [...seats.filter(other => other !== alike), seat]
118}
119
120function isAlike(one: Seat, other: Seat): boolean {
121  return one.canType === other.canType && one.isFocused === other.isFocused && one.isInline === other.isInline
122}
123
124const TOOLS: readonly ToolSpec[] = [
125  {
126    name: 'assign_task',
127    description: [
128      'Give the user a task that only they can do, and keep it in front of them until they act on it.',
129      'Use it for a secret or credential they must put in place, an action on their machine or on an account you cannot reach (a dashboard, a device, a deploy approval), a decision that is theirs to make, or a review or approval of your work.',
130      'Assign it even when you also ask in your reply: the user may be busy with other things, and the task keeps the ask in front of them.',
131      'A task does not block: you keep working while it waits, and the response reaches you whenever the user gets to it, so it suits anything you need from them at some point in the session.',
132      'AskUserQuestion is the blocking kind: it waits for the answer, so it suits what you need before you can go on.',
133      'One task per need: list_tasks shows what is already open.',
134      'Write the title as an imperative the user can act on without scrolling back.',
135      'For a secret, ask the user to put it where it belongs and mark the task done, rather than paste it.',
136      'The user sees open tasks in their My tasks pane, or opens it with /my-tasks.',
137      'The user rejects (with a reason) or fulfills it (done, an option, or an answer in their words). Their response reaches you as a message, or when you call list_tasks.',
138    ].join(' '),
139    inputSchema: {
140      type: 'object',
141      properties: {
142        title: {
143          type: 'string',
144          description: 'What the user should do, as an imperative they can act on without scrolling back. Under 80 characters.',
145        },
146        why: {
147          type: 'string',
148          description: 'One sentence: what it unblocks, or why only the user can do it.',
149        },
150        done_when: {
151          type: 'string',
152          description: "Optional: what counts as done. For a secret: \"It is in .env. Don't paste it here.\"",
153        },
154        kind: {
155          type: 'string',
156          enum: ['do', 'answer', 'choose'],
157          description: 'do: the user does something and marks it done. answer: you need their words (an error, a log, test results). choose: they pick one of options.',
158        },
159        options: {
160          type: 'array',
161          items: { type: 'string' },
162          minItems: 2,
163          maxItems: 4,
164          description: 'For choose only: 2 to 4 short options.',
165        },
166      },
167      required: ['title', 'why', 'kind'],
168    },
169  },
170  {
171    name: 'list_tasks',
172    description: [
173      'List the tasks you gave the user and what they did with them: accepted, done (with their answer or choice), rejected (with their reason).',
174      'Call it when you are about to need a task\'s result, when told an answer is saved for you, or before assigning, to avoid a duplicate.',
175    ].join(' '),
176    inputSchema: {
177      type: 'object',
178      properties: {
179        show: {
180          type: 'string',
181          enum: ['updates', 'open', 'all'],
182          description: 'updates (the default): open tasks and responses you have not seen. open: open tasks only. all: every task this session.',
183        },
184        id: { type: 'number', description: 'One task, whole, by its number.' },
185      },
186    },
187  },
188  {
189    name: 'withdraw_task',
190    description: 'Take back a task you gave the user when you no longer need it: you found another way, or the plan changed. The user sees the reason.',
191    inputSchema: {
192      type: 'object',
193      properties: {
194        id: { type: 'number', description: 'The task\'s number.' },
195        reason: { type: 'string', description: 'One short sentence the user sees.' },
196      },
197      required: ['id'],
198    },
199  },
200]
201
202const tasks = atom({ plugin: 'human-in-the-loop', key: 'tasks' } as const, [] as readonly Task[])
203const nextId = atom({ plugin: 'human-in-the-loop', key: 'nextId' } as const, 1)
204const took = atom({ plugin: 'human-in-the-loop', key: 'took' } as const, {} as Readonly<Record<string, Took>>)
205const selectedId = atom({ plugin: 'human-in-the-loop', key: 'selectedId' } as const, null as number | null)
206const editing = atom({ plugin: 'human-in-the-loop', key: 'editing' } as const, null as Editing | null)
207const loadedFor = atom({ plugin: 'human-in-the-loop', key: 'loadedFor' } as const, null as string | null)
208const isWorking = atom({ plugin: 'human-in-the-loop', key: 'isWorking' } as const, false)
209/** The remote clients attached, by surface, as the state's contract declares them. */
210type Roster = StateValue<'human-in-the-loop', 'clients'>
211/** The roster, kept where a reload of the code finds it. */
212const clients = atom({ plugin: 'human-in-the-loop', key: 'clients' } as const, {} as Roster)
213
214/**
215 * Send now goes to Claude as a message (`auto` while it is idle), Save for
216 * later waits (`auto` while it works) until its turn ends with every task
217 * answered, a later answer while it is idle, or the user's next prompt.
218 */
219type How = 'auto' | 'now' | 'later'
220
221/**
222 * What a toast says when a prompt carrying updates is dropped: why (`why`,
223 * the mod's own prompt, which the user didn't type), only that they're kept
224 * (`kept`, an answer the user typed, whose drop the engine shows), or nothing
225 * (`nothing`, the user's own prompt, which they rode: they wait as before).
226 */
227type DropNote = 'why' | 'kept' | 'nothing'
228
229/** A prompt as it entered: its words, and the blocks that go beside them. */
230type Entered = { text: string; context?: readonly string[] }
231
232/**
233 * What a sync changed of what the session shows: nothing (`same`), the tasks
234 * another session took on (`lost`), or everything, taking the project on
235 * (`joined`).
236 */
237type Synced = 'same' | 'lost' | 'joined'
238
239/** What the module tracks beside `$.state`; a hot reload starts it over. */
240const live = {
241  sessionId: '',
242  root: '',
243  /** The folder the latest join is for, set as it is asked: `root` follows in queue order. */
244  joinRoot: '',
245  /** A Send now row joined the running turn and no step has read it yet. */
246  isUnread: false,
247  /** A Send now the running turn could not take: it goes once the turn ends. */
248  isSendingAtEnd: false,
249  /** What the user has typed in each field so far, by `fieldKeyOf`. */
250  drafts: new Map<string, string>(),
251  /**
252   * What was typed in each answer field as its task closed, by `fieldKeyOf`:
253   * a button pressed on a drawing from before the task closed answers with it.
254   */
255  closed: new Map<string, string>(),
256  /**
257   * What each surface draws each field with, by `fieldKeyOf`: the draft as
258   * the surface first drew it. It stays put while the field is typed in, as a
259   * value drawn anew puts the field's text back to it, keys typed meanwhile
260   * lost. A surface that forgets what its fields hold (the pane closed, or a
261   * client of it came) draws them with the draft again.
262   */
263  drawn: new Map<RenderSurface, Map<string, string>>(),
264  batch: null as Timer | null,
265  /** Says in the project's store that this session is alive. */
266  heartbeat: null as Timer | null,
267  /** Tasks waiting in the project's other live sessions. */
268  elsewhere: 0,
269  /** The project's next task number at its last reading. */
270  floor: 1,
271  /** A 0.1.4 session was alive in the project at its last reading. */
272  hasLegacyPeer: false,
273  /** The session has a slot in the project's store: it writes it, its count in it, until it ends. */
274  hasSlot: false,
275  /** When the session's slot was last written. */
276  writtenMs: 0,
277  /** When the session last read the project. */
278  readMs: 0,
279  /** Set once the session ended: its slot says so from then on. */
280  endedMs: undefined as number | undefined,
281  /** How many sessions of the process have ended: one that ends before its join comes up in the queue stays ended. */
282  ends: 0,
283  /** Responses a prompt entered without, by `updateKeyOf`: they go with Send now, the next prompt or another response, never alone as a turn ends. */
284  held: new Set<string>(),
285  /** Joins into another folder not done yet: until then the tasks the process holds are the folder's it leaves. */
286  moving: 0,
287  /** The store work asked for and not yet done: each piece waits for the one before. */
288  queue: Promise.resolve() as Promise<unknown>,
289  /** Store work a wait gave up on, not settled yet: while there is any, nothing waits on the store. */
290  stalled: 0,
291  /** The roster's writes asked for and not yet done: each waits for the one before (see `rostered`). */
292  rosterQueue: Promise.resolve() as Promise<unknown>,
293  /**
294   * Turns begun and not yet ended. `turn.start` names no loop, so a loop
295   * other than main's (an engine side request, a teammate) may begin one that
296   * ends under an agent id: each ends by its own id.
297   */
298  turns: new Set<string>(),
299  /** Whether a turn runs, in the engine's own word (the band's `isWorking`), once it has said. */
300  engineWorking: undefined as boolean | undefined,
301  /**
302   * How each surface drawing the pane draws it, by `e.surface`: as it last
303   * did, or, drawn by two clients or more, every way since one came or went
304   * (by `seatsWith`), since a render names no client.
305   */
306  seats: new Map<RenderSurface, readonly Seat[]>(),
307  /** Surfaces a client left while others stay: the next drawing there starts their seats over. */
308  startingOver: new Set<RenderSurface>(),
309  /** How many times each surface's last client has left: a drawing under way as one did keeps no seat there. */
310  emptied: new Map<RenderSurface, number>(),
311  /** The key of the element the pane's focus ring last moved onto. */
312  ring: undefined as string | undefined,
313  /** The rows the pane last asked for. */
314  rows: 0,
315  /** How many times the mod closed the pane: a re-size under way leaves it closed (see `fit`). */
316  closes: 0,
317  /** The re-sizes keys and ring moves asked for and not yet done: each waits for the one before (see `refit`). */
318  refitQueue: Promise.resolve() as Promise<unknown>,
319}
320
321/** Whether Claude is at work: the engine's word when it has given one, else the turns begun and not ended. */
322function working(): boolean {
323  return live.engineWorking ?? live.turns.size > 0
324}
325
326export const register: Register = on => {
327  on('session.start', async ($, e, next) => {
328    for (const tool of TOOLS) {
329      await $.tool.register(tool)
330    }
331
332    await $.command.register({ name: 'my-tasks', description: 'Show the tasks Claude gave you' })
333    await join($)
334
335    return next(e)
336  })
337
338  // An ended session's tasks wait in the store for the next session in the
339  // project. After /clear or a resume the process goes on as another session
340  // with no session.start, so it joins the project again here.
341  on('session.end', async ($, e, next) => {
342    live.heartbeat?.cancel()
343    live.heartbeat = null
344    live.endedMs = await $.clock.now()
345    live.ends += 1
346    const ends = live.ends
347
348    // The slot marked ended, in one write and no read, once the store work in
349    // flight is done; a session that never read the project reads it first.
350    // The exit's budget is short, and the end waits for the write only
351    // through half of what is left: a slot not written by then goes stale,
352    // and the next session takes it on then. A process that goes on makes
353    // the write all the same, before it joins again.
354    const written = queued(async () => ((await isLoaded($)) ? writeOwn($) : load($))).catch(() => undefined)
355    const leftMs = next.budget.remainingMs
356
357    await (Number.isFinite(leftMs) ? Promise.race([written, $.clock.sleep(leftMs / 2)]) : written)
358
359    const ended = await next(e)
360
361    if (e.reason === 'clear' || e.reason === 'resume') {
362      // With the count as this session ended: the next one, ending before
363      // the join runs, stays ended.
364      $.clock.after(0, () => void join($, ends))
365    }
366
367    return ended
368  })
369
370  on('command.run', { command: 'my-tasks' }, async $ => {
371    await wake($)
372
373    if ((await read($, tasks)).filter(isShown).length === 0) {
374      return { text: 'No tasks for you right now.' }
375    }
376
377    await show($, true)
378
379    return {}
380  })
381
382  // The tools stay in the prompt's list, descriptions and all, where an MCP
383  // tool would wait behind ToolSearch: the description is what steers Claude
384  // to assign a task, so the ask stays in front of the user.
385  on('tool.describe', { tool: ASSIGN }, async ($, e, next) => ({ ...(await next(e)), isDeferred: false }))
386  on('tool.describe', { tool: LIST }, async ($, e, next) => ({ ...(await next(e)), isDeferred: false }))
387  on('tool.describe', { tool: WITHDRAW }, async ($, e, next) => ({ ...(await next(e)), isDeferred: false }))
388
389  on('tool.call', { tool: ASSIGN }, async ($, e) => {
390    if (e.agentId !== undefined) {
391      return { deny: 'Only the main agent assigns tasks to the user. Say what you need from the user in your result instead.' }
392    }
393
394    const ask = parseAsk(e as unknown as Record<string, unknown>)
395
396    if ('error' in ask) {
397      return { deny: ask.error }
398    }
399
400    // Resumed into another folder, the session takes it on once the store
401    // work in flight is done and it has read it. A task assigned before then
402    // is the old folder's: the join drops it here, and the old session's end
403    // write may leave it there.
404    if (live.moving > 0) {
405      return { deny: MOVING }
406    }
407
408    // Task numbers count per project, across its sessions: the next is past
409    // every number a session there drew, which each slot carries, so this
410    // reads the project first (and lets go of tasks taken on while the
411    // session slept). Two sessions assigning at the same moment can still
412    // draw one number; each shows and answers only its own, and where their
413    // tasks meet (one taking on the other's), `adopt` gives the later a new one.
414    await beat($, false)
415
416    const active = (await read($, tasks)).filter(isActive)
417    const same = active.find(task => sameAsk(task.title, ask.title))
418
419    if (same !== undefined) {
420      return { result: `Task #${same.id} already asks the user for this ("${same.title}"); nothing new was assigned.` }
421    }
422
423    if (active.length >= MAX_OPEN) {
424      return {
425        deny: `The user already has ${MAX_OPEN} open tasks. Withdraw one you no longer need, or wait for them to act (list_tasks shows them).`,
426      }
427    }
428
429    const id = (await update($, nextId, n => Math.max(n, live.floor) + 1)) - 1
430    const nowMs = await $.clock.now()
431    const task: Task = {
432      id,
433      ...ask,
434      state: 'open',
435      update: 'none',
436      // The conversation's own: until it joins the project (a store slow
437      // after /clear), the process still acts for the one it left.
438      sessionId: await $.session.id(),
439      createdMs: nowMs,
440      updatedMs: nowMs,
441    }
442
443    await change($, list => [...list, task])
444
445    if (live.hasLegacyPeer) {
446      await awaited($, queued(() => editLegacy($, { removed: [], taken: {} })))
447    }
448
449    await update($, selectedId, chosen => chosen ?? id)
450
451    if (!(await show($, false))) {
452      $.ui.toast(`Claude assigned you a task: ${printable(task.title, MAX_TITLE)}. See /my-tasks`)
453    }
454
455    return { result: assignedOf(task, active.length + 1) }
456  })
457
458  on('tool.call', { tool: LIST }, async ($, e) => {
459    if (live.moving > 0) {
460      return { deny: MOVING }
461    }
462
463    await wake($)
464    const args = e as unknown as Record<string, unknown>
465    const id = typeof args['id'] === 'number' ? args['id'] : undefined
466    const scope = args['show'] === 'open' || args['show'] === 'all' ? args['show'] : 'updates'
467    const list = await read($, tasks)
468
469    const picked =
470      id !== undefined
471        ? list.filter(task => task.id === id)
472        : scope === 'all'
473          ? list
474          : scope === 'open'
475            ? list.filter(isActive)
476            : list.filter(isShown)
477
478    if (id !== undefined && picked.length === 0) {
479      return { result: `No task #${id}.` }
480    }
481
482    // A subagent's read tells the main agent nothing. Claude hears the
483    // responses this shows: one that came in after it read goes later.
484    if (e.agentId === undefined) {
485      await claim($, task => picked.some(one => one.id === task.id && one.update === 'pending'))
486    }
487
488    return { result: listOf(picked, await $.clock.now()) }
489  })
490
491  on('tool.call', { tool: WITHDRAW }, async ($, e) => {
492    if (e.agentId !== undefined) {
493      return { deny: 'Only the main agent withdraws tasks.' }
494    }
495
496    if (live.moving > 0) {
497      return { deny: MOVING }
498    }
499
500    await wake($)
501    const args = e as unknown as Record<string, unknown>
502    const id = args['id']
503    const reason = typeof args['reason'] === 'string' ? oneLine(args['reason']) : ''
504    const task = (await read($, tasks)).find(one => one.id === id)
505    // Withdrawn only while it is open: an answer the user gave a moment before stands.
506    const found =
507      task === undefined || !isActive(task)
508        ? task
509        : await edit($, task.id, one => ({
510            ...one,
511            state: 'withdrawn',
512            update: 'delivered',
513            ...(reason === '' ? {} : { reason }),
514          }))
515
516    if (found === undefined) {
517      return { deny: `No task #${String(id)}.` }
518    }
519
520    if (!isActive(found)) {
521      return { deny: `Task #${found.id} is already ${found.state}; there is nothing to withdraw.` }
522    }
523
524    // Its fields go with it, and what was typed in them: put in the prompt
525    // box unasked, it would join whatever the user is writing there.
526    await settle($, found.id)
527    const why = reason === '' ? '' : `. ${printable(reason, 200)}`
528    $.ui.toast(`Claude withdrew the task: ${printable(found.title, MAX_TITLE)}${why}`, { timeoutMs: 8000 })
529
530    return { result: `Withdrew task #${found.id}; it is gone from the user's My tasks pane.` }
531  })
532
533  on('turn.start', async ($, e, next) => {
534    live.isUnread = false
535    live.turns.add(e.turnId)
536    await syncWorking($)
537
538    return next(e)
539  })
540
541  on('turn.step', async function* ($, e, next) {
542    if (e.agentId === undefined) {
543      live.isUnread = false
544    }
545
546    return yield* next(e)
547  })
548
549  on('turn.complete', async ($, e, next) => {
550    const result = await next(e)
551
552    // Main's turn ending ends every turn; another loop's ends its own.
553    if (e.agentId === undefined) {
554      live.turns.clear()
555      live.engineWorking = false
556    } else {
557      live.turns.delete(e.turnId)
558    }
559
560    await syncWorking($)
561
562    if (e.agentId === undefined) {
563      // Answers saved while Claude worked go now that it's free, unless a
564      // task is still open: then they go with that last answer, together.
565      // One a prompt entered without goes with them, but sends nothing alone.
566      const all = await read($, tasks)
567      const isAllAnswered = all.some(task => task.update === 'pending' && !live.held.has(updateKeyOf(task))) && !all.some(isActive)
568
569      if (live.isSendingAtEnd || isAllAnswered) {
570        live.isSendingAtEnd = false
571        // This message wakes Claude, which reads any row it missed above it.
572        live.isUnread = false
573        void send($, true)
574      } else if (live.isUnread) {
575        // A Send now that joined the turn during its final reply sits in the
576        // conversation with no step left to read it: wake Claude up for it.
577        live.isUnread = false
578        void $.prompt.submit({ text: 'I answered a task while you were finishing your reply; my answer is above.', asUser: true })
579      }
580    }
581
582    return result
583  })
584
585  // Draws nothing and passes the band on: it only reads the engine's word on
586  // whether a turn runs, which no turn event gives for every loop.
587  on('ui.render', { component: 'AbovePrompt' }, ($, e, next) => {
588    if (live.engineWorking !== e.props.isWorking) {
589      live.engineWorking = e.props.isWorking
590      $.clock.after(0, () => void syncWorking($))
591    }
592
593    return next(e)
594  })
595
596  on('prompt.submit', async ($, e, next) => {
597    if ((e.origin.kind === 'plugin' && e.origin.name === PLUGIN) || live.moving > 0) {
598      return next(e)
599    }
600
601    await wake($)
602    const bridged = answerIn(e.text)
603    const task = bridged === null ? undefined : (await read($, tasks)).find(one => one.id === bridged.id && isActive(one))
604    let isAnswered = false
605
606    if (bridged !== null && task !== undefined) {
607      if (looksSecret(bridged.answer)) {
608        return {
609          drop: `This looks like a secret, so it wasn't sent. Put it where it belongs, then mark #${task.id} Done.`,
610        }
611      }
612
613      const given = bridged.answer === '' ? {} : { answer: bridged.answer }
614
615      if (e.turnId === undefined) {
616        // Claude is idle: this prompt is the answer, sent with every other
617        // update Claude has not heard, those a batch was about to send among them.
618        live.batch?.cancel()
619        live.batch = null
620      }
621
622      // A task closed meanwhile (Claude withdrew it, say) keeps no answer:
623      // the prompt goes as typed.
624      const was = await resolve($, task.id, { state: 'done', ...given }, 'later')
625      isAnswered = was !== undefined && isActive(was)
626
627      if (isAnswered && e.turnId !== undefined) {
628        const when = (await read($, tasks)).some(isActive) ? 'with your other answers' : 'when this turn ends'
629
630        return {
631          drop: `Saved as your answer to #${task.id}. Claude gets it ${when}, or press Send now in /my-tasks.`,
632        }
633      }
634    }
635
636    const due = await claim($)
637    // A task still here has its answer in this prompt, or in another send
638    // that took it as it was saved. One gone meanwhile (another session took
639    // it on) leaves the prompt as typed.
640    const isAnswer = isAnswered && task !== undefined && (await read($, tasks)).some(one => one.id === task.id)
641
642    if (isAnswer && due.length === 0) {
643      return { drop: `Your answer to #${task.id} already went to Claude.` }
644    }
645
646    if (due.length === 0) {
647      return next(e)
648    }
649
650    if (isAnswer) {
651      return passOn($, due, inWords, 'kept', () => next({ ...e, text: messageOf(due) }))
652    }
653
654    return passOn($, due, inDigest, 'nothing', () => next({ ...e, context: [...(e.context ?? []), digestOf(due)] }))
655  })
656
657  // Read at a conversation's start and again after a compaction: what is
658  // still with the user, so Claude neither forgets nor assigns it twice.
659  // Added last, on the session's side of the cache boundary, wherever the
660  // tool can be reached: offered outright, or found through ToolSearch.
661  on('prompt.compose', async ($, e, next) => {
662    const composed = await next(e)
663    const isReachable = e.tools.some(tool => tool === ASSIGN || tool === 'ToolSearch')
664
665    if (!isReachable || e.traits.includes('print') || e.traits.includes('bare')) {
666      return composed
667    }
668
669    return { sections: [...composed.sections, { id: 'human-in-the-loop:tasks', text: STEERING, scope: 'session' }] }
670  })
671
672  on('prompt.context', async ($, e, next) => {
673    const result = await next(e)
674    const shown = (await read($, tasks)).filter(isShown)
675
676    if (shown.length === 0 || live.moving > 0) {
677      return result
678    }
679
680    return { ...result, blocks: [...result.blocks, { name: 'humanInTheLoop', text: contextOf(shown, await $.session.id()) }] }
681  })
682
683  on('ui.render', { component: 'ToolUse', props: { tool: ASSIGN } }, ($, e, next) => {
684    const input = e.props.input as Record<string, unknown> | null | undefined
685    const title = typeof input?.['title'] === 'string' ? input['title'] : ''
686
687    if (title === '' || e.props.isErrored || e.props.isInterrupted) {
688      return next(e)
689    }
690
691    const { Text } = $.ui.resolve(e)
692
693    return (
694      // One text, so the label keeps its words whole and the title wraps after it.
695      <Text wrap="wrap">
696        <Text color="yellow">{'☐ '}</Text>
697        <Text bold>{'Assigned you a task: '}</Text>
698        {printable(title, MAX_SHOWN_TITLE)}
699      </Text>
700    )
701  })
702
703  // A second client on a surface (two phones) draws the pane at a width of
704  // its own, and its fields with what is typed in them so far: it is counted
705  // before it draws.
706  on('session.attach', async ($, e, next) => {
707    live.drawn.delete(e.surface)
708    await rostered($, all => ({ ...all, [e.surface]: [...new Set(all[e.surface]).add(e.clientId)] }))
709    return next(e)
710  })
711
712  // A client gone, the pane fits the ones left, which draw it again as the
713  // roster changes: no render says which of its surface's seats was its own,
714  // so they start over, and go with the last client. Both happen ahead of the
715  // write that wakes the drawings, which fit the pane to what is left.
716  on('session.detach', async ($, e, next) => {
717    await rostered($, all => {
718      const left = (all[e.surface] ?? []).filter(id => id !== e.clientId)
719
720      if (left.length > 0) {
721        live.startingOver.add(e.surface)
722      } else {
723        live.seats.delete(e.surface)
724        live.emptied.set(e.surface, (live.emptied.get(e.surface) ?? 0) + 1)
725      }
726
727      return { ...all, [e.surface]: left }
728    })
729
730    return next(e)
731  })
732
733  // The ring on the open field lets the terminal wrap what is typed there:
734  // the pane asks for the rows that takes, and for one row once it leaves.
735  on('ui.focus', { requestId: PANE }, async ($, e, next) => {
736    const moved = await next(e)
737
738    if (moved.deny === undefined) {
739      live.ring = e.element
740      void refit($)
741    }
742
743    return moved
744  })
745
746  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
747    const emptied = live.emptied.get(e.surface)
748    const elements = $.ui.resolve(e)
749    const { Box, Text, Button } = elements
750    // The mobile app draws no field yet: answers and reasons wait for a surface
751    // that does. The engine fills an element a surface lacks with one that draws
752    // nothing, so the surface says, not the table.
753    const Input = e.surface !== 'mobile' && 'Input' in elements ? elements.Input : undefined
754    const view = await paneView($, { canType: Input !== undefined, isFocused: e.props.isFocused })
755
756    // The pane asks for the rows its tree takes at the width each surface
757    // draws it in: a long title wraps, and a pane sized for one row would cut
758    // off the rest.
759    const columns = e.props.bodyColumns
760    const seat: Seat = { columns, canType: view.canType, isFocused: view.isFocused, isInline: e.props.placement === 'inline' }
761    // Drawn by two clients, a surface keeps how each drew it, or each one's
762    // drawing would resize the pane against the other's: as a render names
763    // neither, every way it was drawn since a client came or went. One drawn
764    // as the surface's last client left keeps no seat, which nothing there
765    // would draw again to take back.
766    const isShared = ((await read($, clients))[e.surface]?.length ?? 0) > 1
767    // A surface that docks the pane it seated inline asks for the rows of
768    // those that still seat it inline.
769    const wasInline = (live.seats.get(e.surface) ?? []).some(one => one.isInline)
770
771    if (live.emptied.get(e.surface) === emptied) {
772      const kept = live.startingOver.delete(e.surface) ? [] : (live.seats.get(e.surface) ?? [])
773      live.seats.set(e.surface, isShared ? seatsWith(kept, seat) : [seat])
774    }
775
776    const { shown, editing: field, isWorking: working } = view
777
778    // The pane is closing: it asks for no rows, which would open it again.
779    if (shown.length === 0) {
780      return <Text dimColor>No tasks for you right now.</Text>
781    }
782
783    if (seat.isInline || wasInline) {
784      const rows = await rowsWanted($, view)
785
786      if (rows !== live.rows) {
787        void fit($, rows)
788      }
789    }
790
791    const active = shown.filter(isActive)
792    const saved = shown.filter(task => !isActive(task))
793    const selected = selectedOf(view)
794    const head = headlineOf(view)
795
796    // The glyph keeps its cells beside a title that wraps.
797    const glyph = (
798      <Box flexShrink={0}>
799        <Text color="yellow">{'☐ '}</Text>
800      </Box>
801    )
802
803    // The title and its age are one text, so a long title wraps under itself
804    // and the age follows it, never squeezed into a column of its own.
805    const titleText = (task: Task, isBold: boolean) => (
806      <Text wrap="wrap">
807        <Text bold={isBold}>{titleOf(task)}</Text>
808        <Text dimColor>{ageOf(task, view)}</Text>
809      </Text>
810    )
811
812    const actionsOf = (task: Task) => (
813      <Box key="actions" flexDirection="row" flexWrap="wrap" columnGap={BUTTON_GAP}>
814        {actionsFor(task, view.canType).map(action => (
815          <Button
816            key={action.key}
817            plain
818            hotkey={action.hotkey}
819            label={action.label}
820            onPress={() => {
821              if (action.option !== undefined) {
822                return respond($, task.id, { state: 'done', answer: action.option }, 'auto')
823              }
824
825              if (action.key === 'done') {
826                return respond($, task.id, { state: 'done' }, 'auto')
827              }
828
829              if (action.key === 'answer') {
830                return startEditing($, task.id, 'answer')
831              }
832
833              return view.canType ? startEditing($, task.id, 'reason') : respond($, task.id, { state: 'rejected' }, 'auto')
834            }}
835          />
836        ))}
837      </Box>
838    )
839
840    const answerField = (task: Task, held: string | undefined): Controls => {
841      if (Input === undefined) {
842        return [null, null]
843      }
844
845      if (held !== undefined) {
846        return [
847          null,
848          <Box key="held" flexDirection="column">
849            <Text color="yellow" wrap="wrap">
850              {HELD}
851            </Text>
852            <Box flexDirection="row" flexWrap="wrap" columnGap={BUTTON_GAP}>
853              <Button key="edit" plain label="Edit" onPress={() => startEditing($, task.id, 'answer')} />
854              <Button key="send-anyway" plain label="Send anyway" onPress={() => answer($, task.id, held, 'auto', true)} />
855            </Box>
856          </Box>,
857        ]
858      }
859
860      const key = fieldKeyOf({ id: task.id, field: 'answer' })
861      const submitLabel = submitLabelOf('answer', view)
862      const [otherWay, long, cancel] = answerButtonsOf(view)
863
864      return [
865        <Input
866          key={key}
867          label={ANSWER_LABEL}
868          placeholder={placeholderOf(answerPlaceholderOf(view), ANSWER_LABEL, submitLabel, columns)}
869          value={fieldValueOf(e.surface, key)}
870          submitLabel={submitLabel}
871          autoFocus
872          onInput={value => typed($, key, value)}
873          onSubmit={value => answer($, task.id, value, 'auto')}
874        />,
875        <Box key="buttons" flexDirection="row" flexWrap="wrap" columnGap={BUTTON_GAP}>
876          <Button key="other-way" plain label={otherWay} onPress={() => answerTyped($, task.id, working ? 'now' : 'later')} />
877          <Button key="long" plain label={long} onPress={() => longAnswer($, task.id)} />
878          <Button key="cancel" plain label={cancel} onPress={() => stopEditing($)} />
879        </Box>,
880      ]
881    }
882
883    const reasonField = (task: Task): Controls => {
884      if (Input === undefined) {
885        return [null, null]
886      }
887
888      const key = fieldKeyOf({ id: task.id, field: 'reason' })
889      const submitLabel = submitLabelOf('reason', view)
890
891      return [
892        <Input
893          key={key}
894          label={REASON_LABEL}
895          placeholder={placeholderOf(REASON_PLACEHOLDER, REASON_LABEL, submitLabel, columns)}
896          value={fieldValueOf(e.surface, key)}
897          submitLabel={submitLabel}
898          autoFocus
899          onInput={value => typed($, key, value)}
900          onSubmit={value => {
901            const reason = oneLine(value)
902            return respond($, task.id, { state: 'rejected', ...(reason === '' ? {} : { reason }) }, 'auto', reason)
903          }}
904        />,
905        <Button key="cancel" plain label="Cancel" onPress={() => stopEditing($)} />,
906      ]
907    }
908
909    const selectedRows = (task: Task) => {
910      // A field open on a surface that draws one: elsewhere the task keeps its buttons.
911      const isEditing = view.canType && field !== null && field.id === task.id
912      const [input, buttons]: Controls = !isEditing
913        ? [null, actionsOf(task)]
914        : field.field === 'answer'
915          ? answerField(task, field.held)
916          : reasonField(task)
917      const doneWhen = doneWhenOf(task)
918
919      // The terminal sizes a field by the pane's body, whatever box holds it:
920      // it goes out of the task's indent, across the body's whole width.
921      return (
922        <Box key={`task-${task.id}`} flexDirection="column" flexShrink={0}>
923          <Box flexDirection="row">
924            {glyph}
925            {titleText(task, true)}
926          </Box>
927          <Box flexDirection="column" paddingLeft={2}>
928            <Text wrap="wrap">{whyOf(task)}</Text>
929            {doneWhen === undefined ? null : (
930              <Text dimColor wrap="wrap">
931                {doneWhen}
932              </Text>
933            )}
934          </Box>
935          {input}
936          <Box flexDirection="column" paddingLeft={2}>
937            {buttons}
938          </Box>
939        </Box>
940      )
941    }
942
943    const taskRows = active.map(task =>
944      task.id === selected?.id ? (
945        selectedRows(task)
946      ) : (
947        <Box key={`task-${task.id}`} flexDirection="row" flexShrink={0}>
948          {glyph}
949          <Box flexShrink={0}>
950            <Button key={`select-${task.id}`} plain dimColor label={`#${task.id}`} onPress={() => select($, task.id)} />
951          </Box>
952          <Text dimColor wrap="wrap">
953            {` ${nameOf(task)}${ageOf(task, view)}`}
954          </Text>
955        </Box>
956      ),
957    )
958
959    const savedRows = saved.map((task, i) => (
960      <Box key={`saved-${task.id}`} flexDirection="row" flexShrink={0}>
961        <Box flexShrink={0}>{task.state === 'rejected' ? <Text color="red">{'✗ '}</Text> : <Text color="green">{'✓ '}</Text>}</Box>
962        <Text dimColor wrap="wrap">
963          {savedOf(task)}
964        </Text>
965        <Box flexShrink={0} marginLeft={2}>
966          <Button key={`send-${task.id}`} plain {...sendNowOf(i)} onPress={() => sendNow($)} />
967        </Box>
968      </Box>
969    ))
970
971    return (
972      <Box flexDirection="column">
973        <Box key="head" flexDirection="row" flexShrink={0}>
974          <Text wrap="wrap">
975            <Text color={active.length > 0 ? 'yellow' : 'gray'}>{head.glyph}</Text>
976            <Text bold>{head.headline}</Text>
977            <Text dimColor>{head.note}</Text>
978          </Text>
979        </Box>
980        <Box key="tasks" flexDirection="column" marginTop={1} flexShrink={0}>
981          {taskRows}
982          {savedRows}
983        </Box>
984        <Box key="foot" flexDirection="row" marginTop={1} columnGap={BUTTON_GAP} flexShrink={0}>
985          <Text dimColor wrap="wrap">
986            {hintOf(view)}
987          </Text>
988          <Box flexShrink={0}>
989            <Button key="hide" plain dimColor role="dismiss" label={HIDE} onPress={() => closePane($)} />
990          </Box>
991        </Box>
992      </Box>
993    )
994  })
995}
996
997/** Keeps the pane's word on whether Claude works (Enter sends, or saves) in step. */
998async function syncWorking($: EngineInterface) {
999  const now = working()
1000
1001  await update($, isWorking, () => now)
1002}
1003
1004/**
1005 * Joins the project as this session: takes on its tasks, the store's slot
1006 * kept alive by a heartbeat, the status line and, for tasks taken on from an
1007 * earlier session, the pane.
1008 */
1009async function join($: EngineInterface, ends = live.ends) {
1010  const sessionId = await $.session.id()
1011  const root = await $.session.root()
1012  // From the folder the latest join is for: one still queued takes the process there first.
1013  const isMoving = live.joinRoot !== '' && live.joinRoot !== root
1014  live.joinRoot = root
1015
1016  // A row of the conversation the process leaves is none of this one's.
1017  live.isUnread = false
1018
1019  // After /clear the process goes on as a new session, with no slot yet: it
1020  // takes over once the old session's writes are done, and takes on what
1021  // the old one held, ended whether or not its end write landed (or, when
1022  // the old one never read the project, what the one before it held).
1023  // Resumed in another folder, it leaves that folder's tasks as its last
1024  // write there left them and starts on this one as a new process would,
1025  // keeping nothing it tracked of that project. A store that fails now
1026  // takes nothing on yet: the session writes nothing until it has read the
1027  // project, which the heartbeat tries again.
1028  const joined = queued(async () => {
1029    if (live.root !== '' && live.root !== root) {
1030      await update($, tasks, () => [])
1031      await update($, nextId, () => 1)
1032      await update($, took, () => ({}))
1033      await update($, selectedId, () => null)
1034      await update($, editing, () => null)
1035      await update($, loadedFor, () => null)
1036      live.drafts.clear()
1037      live.closed.clear()
1038      live.drawn.clear()
1039      live.held.clear()
1040      live.batch?.cancel()
1041      live.batch = null
1042      live.isSendingAtEnd = false
1043      live.elsewhere = 0
1044      live.floor = 1
1045      live.hasLegacyPeer = false
1046    }
1047
1048    live.sessionId = sessionId
1049    live.root = root
1050    live.hasSlot = false
1051    live.writtenMs = 0
1052    live.readMs = 0
1053
1054    // A session that ended while this waited in the queue (an exit right
1055    // after /clear, the store slow) reads the project as an ending session
1056    // does, and its end write, queued after this, marks its slot ended.
1057    if (live.ends === ends) {
1058      live.endedMs = undefined
1059    }
1060
1061    return load($)
1062  }).catch(() => undefined)
1063
1064  if (isMoving) {
1065    live.moving += 1
1066    void joined.then(() => {
1067      live.moving -= 1
1068    })
1069  }
1070
1071  // Tasks from an earlier session: the status line says so, and the pane
1072  // opens where the terminal is wide enough to seat it unasked, unless the
1073  // session has ended since.
1074  const shown = joined
1075    .then(async () => {
1076      if ((await refresh($)) && live.ends === ends) {
1077        await show($, false)
1078      }
1079    })
1080    .catch(() => undefined)
1081
1082  // One that ended before this ran has no heartbeat: its end stopped the last.
1083  if (live.ends === ends) {
1084    live.heartbeat?.cancel()
1085    live.heartbeat = $.clock.every(HEARTBEAT_MS, () => void beat($))
1086  }
1087
1088  // A store slow to answer holds up the start 5 seconds at most: what the
1089  // session takes on shows once it answers.
1090  await awaited($, joined)
1091  await redrawn($, shown)
1092}
1093
1094/**
1095 * Takes on the tasks this session owns in the project's store: its own (a
1096 * resumed session) and those of sessions that ended or went quiet. A live
1097 * session's tasks stay its own: answers go to the session that asked. A hot
1098 * reload keeps the session's tasks as they are.
1099 */
1100async function load($: EngineInterface) {
1101  if (await isLoaded($)) {
1102    await sync($)
1103    return
1104  }
1105
1106  const nowMs = await $.clock.now()
1107  const stored = await readProject($)
1108  const holder = await read($, loadedFor)
1109  const notes = await read($, took)
1110  const count = await read($, nextId)
1111  let project = stored
1112  let adoption!: Adoption
1113  // Tasks the process held that the join numbers anew.
1114  let moves: Move[] = []
1115  // Tasks the process didn't hold: their numbers may have named others here.
1116  let arrived: Task[] = []
1117
1118  // Taken on against the task list as it stands when it changes hands, so a
1119  // press meanwhile is kept. `update` runs this again when another write
1120  // beat it: the last run is the list it wrote. The session's own tasks it
1121  // is done with, which no slot holds, stay in it, with the numbers its
1122  // Claude knows them by.
1123  await update($, tasks, current => {
1124    const done = current.filter(task => task.sessionId === live.sessionId && !isShown(task))
1125    project = withHeld(stored, holder, slotFrom(current, notes, count, nowMs), nowMs)
1126    adoption = adopt(project, live.sessionId, nowMs, done.map(task => task.id), live.endedMs !== undefined, holder)
1127    moves = adoption.renumbered.filter(({ task }) => current.some(one => isSameTask(one, task))).map(({ task, id }) => ({ from: task.id, to: id }))
1128    arrived = adoption.adopted.filter(task => !current.some(one => isSameTask(one, task)) && !moves.some(move => move.to === task.id))
1129
1130    return [...done, ...adoption.adopted].sort((a, b) => a.id - b.id)
1131  })
1132
1133  await renumber($, moves, arrived.map(task => task.id))
1134  live.readMs = nowMs
1135  live.hasSlot ||= live.sessionId in stored.slots
1136  await update($, nextId, n => Math.max(n, adoption.nextId))
1137  await update($, took, () => adoption.took)
1138  await update($, loadedFor, () => live.sessionId)
1139  live.elsewhere = elsewhereIn(project, live.sessionId, nowMs)
1140  live.floor = adoption.nextId
1141  live.hasLegacyPeer = hasLegacyPeer(project, live.sessionId, nowMs)
1142  await reselect($)
1143
1144  try {
1145    // The slot first, noting what it took: only then do the slots it took from leave.
1146    await writeOwn($, adoption.removed.length > 0)
1147    await clean($, project, adoption.removed, adoption.legacy)
1148  } catch {
1149    // What it took on stands, and the caller shows it: the next heartbeat
1150    // makes the writes.
1151  }
1152}
1153
1154/** A task the process held that the join numbered anew: the number it leaves, and the one it takes. */
1155type Move = { from: number; to: number }
1156
1157/**
1158 * Has what the process keeps under task numbers follow its tasks through a
1159 * join. A task it held that the join numbered anew (`moves`) takes its
1160 * drafts, a field open on it, the ring and the selection along. Under the
1161 * numbers of tasks it didn't hold (`arrived`: another session drew the
1162 * number too, or a resumed one did), it lets go of the drafts, what was
1163 * typed as a task under it closed, and a field open on it. Kept, they would
1164 * go with the task that holds the number now.
1165 */
1166async function renumber($: EngineInterface, moves: readonly Move[], arrived: readonly number[]) {
1167  const toOf = (id: number) => moves.find(move => move.from === id)?.to
1168
1169  for (const field of ['answer', 'reason'] as const) {
1170    // Carried first: the number a task leaves may be one another arrived under.
1171    for (const { from, to } of moves) {
1172      const draft = live.drafts.get(fieldKeyOf({ id: from, field }))
1173
1174      if (draft !== undefined) {
1175        live.drafts.set(fieldKeyOf({ id: to, field }), draft)
1176      }
1177
1178      if (live.ring === fieldKeyOf({ id: from, field })) {
1179        live.ring = fieldKeyOf({ id: to, field })
1180      }
1181    }
1182
1183    for (const id of arrived) {
1184      live.drafts.delete(fieldKeyOf({ id, field }))
1185    }
1186  }
1187
1188  for (const id of arrived) {
1189    live.closed.delete(fieldKeyOf({ id, field: 'answer' }))
1190  }
1191
1192  await update($, editing, field => {
1193    if (field === null) {
1194      return null
1195    }
1196
1197    const to = toOf(field.id)
1198    return to !== undefined ? { ...field, id: to } : arrived.includes(field.id) ? null : field
1199  })
1200  await update($, selectedId, id => (id === null ? id : (toOf(id) ?? id)))
hooks/tasks.ts 282 lines
1import type { Task, TaskKind } from '../types'
2import { ago, oneLine, plural, sizeOf } from './text'
3
4/** Open tasks at once; the next is refused. */
5export const MAX_OPEN = 5
6export const MAX_TITLE = 80
7/** The longest why or done-when a task keeps, and the pane draws. */
8export const MAX_WHY = 300
9export const MAX_OPTION = 60
10/** Answers longer than this are named in a digest, not quoted. */
11const MAX_INLINE_ANSWER = 2000
12
13const KINDS: readonly TaskKind[] = ['do', 'answer', 'choose']
14
15/** Still the user's to act on. */
16export function isActive(task: Task): boolean {
17  return task.state === 'open'
18}
19
20/** In the My tasks pane: the user's to act on, or acted on and not yet told to Claude. */
21export function isShown(task: Task): boolean {
22  return isActive(task) || task.update === 'pending'
23}
24
25/** A title as two near-identical asks compare equal. */
26export function sameAsk(a: string, b: string): boolean {
27  const norm = (s: string) => oneLine(s.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, ' '))
28
29  return norm(a) === norm(b)
30}
31
32export type Ask = Pick<Task, 'title' | 'why' | 'doneWhen' | 'kind' | 'options'>
33
34/** Reads `assign_task`'s arguments, or says what is wrong with them. */
35export function parseAsk(args: Record<string, unknown>): Ask | { error: string } {
36  const text = (key: string) => (typeof args[key] === 'string' ? oneLine(args[key] as string) : '')
37  const title = text('title')
38  const why = text('why')
39  const doneWhen = text('done_when')
40  const kind = args['kind'] ?? 'do'
41
42  if (title === '') {
43    return { error: 'title is required: what the user should do, as an imperative.' }
44  }
45
46  if (title.length > MAX_TITLE) {
47    return { error: `title is ${title.length} characters; keep it under ${MAX_TITLE} and put the rest in why.` }
48  }
49
50  if (why === '') {
51    return { error: 'why is required: one sentence on what it unblocks.' }
52  }
53
54  if (!KINDS.includes(kind as TaskKind)) {
55    return { error: 'kind must be "do", "answer" or "choose".' }
56  }
57
58  const raw = Array.isArray(args['options']) ? args['options'] : []
59  const options = raw.filter((o): o is string => typeof o === 'string').map(oneLine).filter(o => o !== '')
60
61  if (kind === 'choose' && (options.length < 2 || options.length > 4)) {
62    return { error: 'a choose task needs 2 to 4 options.' }
63  }
64
65  if (options.some(o => o.length > MAX_OPTION)) {
66    return { error: `keep each option under ${MAX_OPTION} characters.` }
67  }
68
69  return {
70    title,
71    why: why.slice(0, MAX_WHY),
72    ...(doneWhen === '' ? {} : { doneWhen: doneWhen.slice(0, MAX_WHY) }),
73    kind: kind as TaskKind,
74    ...(kind === 'choose' ? { options } : {}),
75  }
76}
77
78/**
79 * What the user did with a task, after its head: their answer, choice or
80 * reason; '' when there is nothing more to say. `isFull` quotes a long
81 * answer whole; a digest names it instead and points at `list_tasks`.
82 */
83function bodyOf(task: Task, isFull: boolean): string {
84  switch (task.state) {
85    case 'rejected':
86      return task.reason ? `The user's reason: "${task.reason}"` : 'No reason given.'
87    case 'withdrawn':
88      return task.reason ? `You withdrew it: ${task.reason}` : 'You withdrew it.'
89    case 'done':
90      if (task.answer === undefined || task.answer === '') {
91        return ''
92      }
93
94      if (task.kind === 'choose' && task.options?.includes(task.answer)) {
95        return `The user chose: ${task.answer}`
96      }
97
98      if (!isFull && task.answer.length > MAX_INLINE_ANSWER) {
99        return `The user's answer (${sizeOf(task.answer.length)}) is saved: call list_tasks with id ${task.id} to read it.`
100      }
101
102      return `The user's answer:\n${task.answer}`
103    default:
104      return ''
105  }
106}
107
108/** How a task's news opens: `#5 done: <title>.` */
109export function newsHeadOf(task: Task): string {
110  return `#${task.id} ${task.state}: ${task.title}.`
111}
112
113/** One task's news for Claude: `#5 done: <title>.` and what the user said. */
114export function newsOf(task: Task, isFull: boolean): string {
115  const body = bodyOf(task, isFull)
116
117  return `${newsHeadOf(task)}${body === '' ? '' : ` ${body}`}`
118}
119
120/** How what the user did with a task opens, in their own words: `#5 <title>:` */
121export function ownHeadOf(task: Task): string {
122  return `#${task.id} ${task.title}:`
123}
124
125/** What the user did with a task, in their own words. */
126function ownWordsOf(task: Task): string {
127  const head = ownHeadOf(task)
128
129  switch (task.state) {
130    case 'rejected':
131      return task.reason ? `${head} I won't do this. ${task.reason}` : `${head} I won't do this.`
132    case 'done':
133      if (task.answer === undefined || task.answer === '') {
134        return `${head} Done.`
135      }
136
137      if (task.kind === 'choose' && task.options?.includes(task.answer)) {
138        return `${head} I chose "${task.answer}".`
139      }
140
141      return `${head}\n${task.answer}`
142    default:
143      return head
144  }
145}
146
147/**
148 * What reaches Claude as a message: every response it has not heard,
149 * whole, in the user's own words, since they are the user's.
150 */
151export function messageOf(due: readonly Task[]): string {
152  const lines = due.map(ownWordsOf)
153
154  return `${due.length === 1 ? 'My response to a task' : 'My responses to tasks'} you gave me (Human in the loop):\n\n${lines.join('\n\n')}`
155}
156
157/** What rides along with the user's next prompt: the updates, long answers named. */
158export function digestOf(due: readonly Task[]): string {
159  const lines = due.map(task => newsOf(task, false))
160
161  return `Task updates since you last checked (Human in the loop):\n${lines.join('\n')}`
162}
163
164/** Read after a compaction or at a session's start: what is still with the user. */
165export function contextOf(shown: readonly Task[], sessionId: string): string {
166  const lines = shown.map(task => {
167    const earlier = task.sessionId === sessionId ? '' : ' (from an earlier session)'
168    return isActive(task) ? `#${task.id} ${task.state}${earlier}: ${task.title}. ${task.why}` : newsOf(task, false)
169  })
170
171  return [
172    'Tasks you gave the user, through the Human in the loop tools (assign_task, list_tasks, withdraw_task):',
173    ...lines,
174    'The user sees them in their My tasks pane, or with /my-tasks. Withdraw any you no longer need.',
175  ].join('\n')
176}
177
178/** `list_tasks`'s answer. */
179export function listOf(tasks: readonly Task[], nowMs: number): string {
180  if (tasks.length === 0) {
181    return 'No tasks match.'
182  }
183
184  return tasks
185    .map(task => {
186      const age = ago(nowMs - task.createdMs)
187      const detail = isActive(task)
188        ? [`Why: ${task.why}`, task.doneWhen ? `Done when: ${task.doneWhen}` : '', task.options ? `Options: ${task.options.join(' | ')}` : '']
189        : bodyOf(task, true).split('\n')
190
191      return [`#${task.id} ${task.state} · assigned ${age === 'now' ? 'just now' : `${age} ago`} · ${task.title}`, ...detail]
192        .filter(line => line.trim() !== '')
193        .join('\n  ')
194    })
195    .join('\n\n')
196}
197
198/** `assign_task`'s answer. */
199export function assignedOf(task: Task, open: number): string {
200  return [
201    `Assigned task #${task.id}: "${task.title}".`,
202    'The user sees it in their My tasks pane, or with /my-tasks, until they act on it. Their response reaches you as a message, or through list_tasks.',
203    'You can carry on with work that does not depend on it.',
204    `Open tasks: ${open} of ${MAX_OPEN}.`,
205  ].join(' ')
206}
207
208/**
209 * The status line under the prompt: this session's tasks and responses not
210 * sent yet, and how many tasks wait in the project's other live sessions,
211 * which this session neither shows nor answers.
212 */
213export function statusOf(shown: readonly Task[], elsewhere = 0): string | undefined {
214  const others = elsewhere > 0 ? `${plural(elsewhere, 'task')} in another session` : ''
215
216  if (shown.length === 0) {
217    return others === '' ? undefined : others
218  }
219
220  const { glyph, headline, note } = waitingOf(shown)
221
222  return [`${glyph}${headline}${note}`, '/my-tasks', others].filter(part => part !== '').join(' · ')
223}
224
225/**
226 * What waits on the user among `shown`, as the status line and the pane's
227 * head lead with it: `☐ 2 tasks for you · 1 not sent yet`, or `✓ 1 not sent
228 * yet` with no task open, the responses named `noun` where there's room.
229 */
230export function waitingOf(shown: readonly Task[], noun?: string): { glyph: string; headline: string; note: string } {
231  const open = shown.filter(isActive).length
232  const saved = shown.length - open
233
234  return {
235    glyph: open > 0 ? '☐ ' : '✓ ',
236    headline: open > 0 ? `${plural(open, 'task')} for you` : `${noun === undefined ? saved : plural(saved, noun)} not sent yet`,
237    note: open > 0 && saved > 0 ? ` · ${saved} not sent yet` : '',
238  }
239}
240
241const BRIDGE = /^\s*↳?\s*Answer to #(\d+):[ \t]*\n?/i
242
243/** What a long answer written in the prompt box starts with. */
244export function bridgeOf(id: number): string {
245  return `↳ Answer to #${id}: `
246}
247
248/** A prompt that answers a task: the task's id and the answer, or null. */
249export function answerIn(text: string): { id: number; answer: string } | null {
250  const match = BRIDGE.exec(text)
251
252  return match ? { id: Number(match[1]), answer: text.slice(match[0].length).trim() } : null
253}
254
255const SECRET_SHAPES: readonly RegExp[] = [
256  /\bsk_(live|test)_[0-9A-Za-z]{10,}/,
257  /\bsk-ant-[\w-]{10,}/,
258  /\bsk-[A-Za-z0-9_-]{20,}/,
259  /\bA(KIA|SIA)[0-9A-Z]{16}\b/,
260  /\bgh[pousr]_[A-Za-z0-9]{30,}/,
261  /\bgithub_pat_[A-Za-z0-9_]{30,}/,
262  /\bxox[abprs]-[\w-]{10,}/,
263  /\bAIza[\w-]{30,}/,
264  /-----BEGIN [A-Z ]*PRIVATE KEY-----/,
265  /\beyJ[\w-]{10,}\.[\w-]{10,}\.[\w-]{10,}/,
266]
267
268/**
269 * Whether an answer looks like it carries a secret: a known key shape, or a
270 * long token mixing upper case, lower case and digits (a git hash, all lower
271 * case hex, is not one).
272 */
273export function looksSecret(text: string): boolean {
274  if (SECRET_SHAPES.some(shape => shape.test(text))) {
275    return true
276  }
277
278  return (text.match(/[A-Za-z0-9+/_=-]{32,}/g) ?? []).some(
279    token => /[a-z]/.test(token) && /[A-Z]/.test(token) && /[0-9]/.test(token),
280  )
281}
282
hooks/pane.ts 272 lines
1import type { Editing, Task } from '../types'
2import { MAX_OPTION, MAX_WHY, isActive, waitingOf } from './tasks'
3import { ago, cellsOf, clip, printable, rowsOf } from './text'
4
5/**
6 * The longest title the pane and the transcript draw. `assign_task` takes
7 * titles of at most MAX_TITLE characters; this bounds what an older version
8 * or another session left in the store, never a title assigned now.
9 */
10export const MAX_SHOWN_TITLE = 300
11
12/** The columns between two buttons in a row of them. */
13export const BUTTON_GAP = 3
14
15/** The cells before a task's text: its glyph, `☐ `. */
16const GLYPH_CELLS = 2
17
18/** The fewest columns the terminal gives a focused field's text, however narrow the pane. */
19const MIN_FIELD_COLUMNS = 12
20
21/**
22 * What the My tasks pane draws from: the tasks, which is selected and which
23 * field is open, and what each row's words depend on. The render hook and
24 * `rowsFor` both read it, so the rows asked for are the rows drawn.
25 */
26export type PaneView = {
27  shown: readonly Task[]
28  selectedId: number | null
29  editing: Editing | null
30  /** The draft in the open field. */
31  draft: string
32  nowMs: number
33  sessionId: string
34  isWorking: boolean
35  /** The surface draws a text field (the mobile app draws none yet). */
36  canType: boolean
37  isFocused: boolean
38  /** The open field has the keys: the terminal wraps what is typed there. */
39  isTyping: boolean
40}
41
42export function selectedOf(view: PaneView): Task | undefined {
43  const active = view.shown.filter(isActive)
44
45  return active.find(task => task.id === view.selectedId) ?? active[0]
46}
47
48/** The pane's head: `☐ 2 tasks for you · 1 not sent yet`, or `✓ 1 response not sent yet`. */
49export function headlineOf(view: PaneView): { glyph: string; headline: string; note: string } {
50  return waitingOf(view.shown, 'response')
51}
52
53/** A task's whole title, safe to draw. */
54export function nameOf(task: Task): string {
55  return printable(task.title, MAX_SHOWN_TITLE)
56}
57
58/** `#3 Rotate the token`: a task's number and its whole title. */
59export function titleOf(task: Task): string {
60  return `#${task.id} ${nameOf(task)}`
61}
62
63/** `  3m · from an earlier session`, drawn dim after an open task's title. */
64export function ageOf(task: Task, view: Pick<PaneView, 'nowMs' | 'sessionId'>): string {
65  const earlier = task.sessionId === view.sessionId ? '' : ' · from an earlier session'
66
67  return `  ${ago(view.nowMs - task.createdMs)}${earlier}`
68}
69
70export function whyOf(task: Task): string {
71  return printable(task.why, MAX_WHY)
72}
73
74export function doneWhenOf(task: Task): string | undefined {
75  return task.doneWhen === undefined ? undefined : `Done when: ${printable(task.doneWhen, MAX_WHY)}`
76}
77
78/** A saved response's row: its task, and that it waits. */
79export function savedOf(task: Task): string {
80  return `${titleOf(task)} · not sent yet`
81}
82
83/** The selected task's buttons, as `hotkey` and `label`. */
84export function actionsOf(task: Task, canType: boolean): { key: string; hotkey: string; label: string; option?: string }[] {
85  const choices =
86    task.kind === 'choose' && task.options !== undefined
87      ? task.options.map((option, i) => ({ key: `option-${i + 1}`, hotkey: String(i + 1), label: printable(option, MAX_OPTION), option }))
88      : [{ key: 'done', hotkey: 'd', label: 'Done' }]
89
90  const typed = canType
91    ? [
92        { key: 'answer', hotkey: 'r', label: task.kind === 'choose' ? 'Other…' : 'Answer…' },
93        { key: 'reject', hotkey: 'x', label: 'Reject…' },
94      ]
95    : [{ key: 'reject', hotkey: 'x', label: 'Reject' }]
96
97  return [...choices, ...typed]
98}
99
100// The terminal draws a field's label as `Answer: `.
101export const ANSWER_LABEL = 'Answer'
102export const REASON_LABEL = 'Reason'
103export const REASON_PLACEHOLDER = 'Optional; Enter rejects it'
104export const HELD =
105  'This looks like a secret. Claude and the transcript on disk would see it. Put it where it belongs and press Done instead.'
106
107export function answerPlaceholderOf(view: PaneView): string {
108  if (!view.isWorking) {
109    return 'Enter sends it to Claude'
110  }
111
112  return view.shown.filter(isActive).length > 1
113    ? 'Enter saves it; Claude gets it with your other answers'
114    : 'Enter saves it; Claude gets it when this turn ends'
115}
116
117/** The answer field's buttons. */
118export function answerButtonsOf(view: PaneView): string[] {
119  return [view.isWorking ? 'Send now' : 'Save for later', 'Long answer…', 'Cancel']
120}
121
122/** The key of task `id`'s field: its own, so no other task's draft, or the focus, lands in it. */
123export function fieldKeyOf(field: Pick<Editing, 'id' | 'field'>): string {
124  return `${field.field}-${field.id}`
125}
126
127/** What Enter does in a field, drawn beside it while it has the keys. */
128export function submitLabelOf(field: Editing['field'], view: Pick<PaneView, 'isWorking'>): string {
129  return field === 'reason' ? 'reject' : view.isWorking ? 'save' : 'send'
130}
131
132/**
133 * The columns the terminal gives a focused field's text: the pane's body,
134 * `columns` across, less the label (`Answer: `) and the hint (` ⏎ send`).
135 */
136export function fieldColumnsOf(label: string, submitLabel: string, columns: number): number {
137  return Math.max(MIN_FIELD_COLUMNS, columns - cellsOf(`${label}: `) - cellsOf(` ⏎ ${submitLabel}`))
138}
139
140/** A placeholder cut to one row of its field, focused or not. */
141export function placeholderOf(text: string, label: string, submitLabel: string, columns: number): string {
142  return clip(text, fieldColumnsOf(label, submitLabel, columns))
143}
144
145/**
146 * Whether the terminal cuts a label `head` cells wide short, with `rest`
147 * cells after it on a row `columns` across, and wraps it onto a second: a row
148 * too narrow takes from the label and what follows it each its share of what
149 * the row lacks, and rounds where the label ends.
150 */
151function isLabelCut(head: number, rest: number, columns: number): boolean {
152  return Math.round((head * columns) / (head + rest)) < head
153}
154
155/**
156 * The rows a field takes across the pane's body, `columns` wide, holding
157 * `text`. The terminal draws its label, the field and, while it has the
158 * keys, the hint on one row, and the label, cut short, wraps onto a second,
159 * as does the hint. Typed in, the field wraps the text a column short of it,
160 * for the cursor; else it cuts the text, or the placeholder, to one row.
161 */
162export function fieldRowsOf(label: string, submitLabel: string, text: string, isTyping: boolean, columns: number): number {
163  const head = cellsOf(`${label}: `)
164  const field = fieldColumnsOf(label, submitLabel, columns)
165
166  if (!isTyping) {
167    // The placeholder is cut to the field.
168    return isLabelCut(head, text === '' ? field : cellsOf(text), columns) ? 2 : 1
169  }
170
171  const rows = text.split('\n').reduce((rows, line) => rows + rowsOf(line, field - 1), 0)
172  // The placeholder cut to the field, or the text and the cursor.
173  const drawn = text === '' ? field : cellsOf(text) + 1
174
175  return Math.max(rows, isLabelCut(head, drawn + cellsOf(` ⏎ ${submitLabel}`), columns) ? 2 : 1)
176}
177
178/** The `i`th saved row's Send now: the first answers `s`. */
179export function sendNowOf(i: number): { hotkey?: string; label: string } {
180  return i === 0 ? { hotkey: 's', label: 'Send now' } : { label: 'Send now' }
181}
182
183/** The `i`th saved row's Send now as the terminal draws it: `s: Send now` on the first. */
184export function sendLabelOf(i: number): string {
185  const { hotkey, label } = sendNowOf(i)
186
187  return hotkey === undefined ? label : `${hotkey}: ${label}`
188}
189
190export function hintOf(view: PaneView): string {
191  return view.isFocused ? 'Esc: back to the prompt' : 'Click, or press ctrl+x tab to use the keys'
192}
193
194export const HIDE = 'Hide'
195
196/** The rows a row of buttons takes in `columns`, wrapping between buttons. */
197export function buttonRowsOf(labels: readonly string[], columns: number): number {
198  let rows = 1
199  let x = 0
200
201  for (const label of labels) {
202    const width = cellsOf(label)
203
204    if (x > 0 && x + BUTTON_GAP + width > columns) {
205      rows += 1
206      x = width
207    } else {
208      x += (x > 0 ? BUTTON_GAP : 0) + width
209    }
210  }
211
212  return rows
213}
214
215/**
216 * The rows the My tasks pane's body takes at `columns` cells across, each
217 * text wrapped as the pane draws it: the head, the selected task whole, a
218 * row (or more, for a long title) for every other task, and the foot; at
219 * most `max`.
220 */
221export function rowsFor(view: PaneView, columns: number, max: number): number {
222  const width = Math.max(1, columns)
223  const inner = Math.max(1, width - GLYPH_CELLS)
224  const active = view.shown.filter(isActive)
225  const saved = view.shown.filter(task => !isActive(task))
226  const selected = selectedOf(view)
227  const head = headlineOf(view)
228  let rows = rowsOf(`${head.glyph}${head.headline}${head.note}`, width) + 1
229
230  for (const task of active) {
231    if (task !== selected) {
232      // `#2` is the button that selects it; the title wraps beside it.
233      rows += rowsOf(` ${nameOf(task)}${ageOf(task, view)}`, Math.max(1, inner - cellsOf(`#${task.id}`)))
234      continue
235    }
236
237    rows += rowsOf(`${titleOf(task)}${ageOf(task, view)}`, inner)
238    rows += rowsOf(whyOf(task), inner)
239    const doneWhen = doneWhenOf(task)
240    rows += doneWhen === undefined ? 0 : rowsOf(doneWhen, inner)
241    rows += controlRowsOf(task, view, width, inner)
242  }
243
244  saved.forEach((task, i) => {
245    rows += rowsOf(savedOf(task), Math.max(1, inner - 2 - cellsOf(sendLabelOf(i))))
246  })
247
248  rows += 1 + rowsOf(hintOf(view), Math.max(1, width - BUTTON_GAP - cellsOf(HIDE)))
249
250  return Math.min(max, rows)
251}
252
253/** The rows under the selected task: its buttons, or its field across the body (`width`) and the buttons under it. */
254function controlRowsOf(task: Task, view: PaneView, width: number, inner: number): number {
255  const field = view.editing !== null && view.editing.id === task.id ? view.editing : null
256
257  if (field === null || !view.canType) {
258    return buttonRowsOf(
259      actionsOf(task, view.canType).map(action => `${action.hotkey}: ${action.label}`),
260      inner,
261    )
262  }
263
264  if (field.held !== undefined) {
265    return rowsOf(HELD, inner) + buttonRowsOf(['Edit', 'Send anyway'], inner)
266  }
267
268  const [label, buttons] = field.field === 'answer' ? [ANSWER_LABEL, answerButtonsOf(view)] : [REASON_LABEL, ['Cancel']]
269
270  return fieldRowsOf(label, submitLabelOf(field.field, view), view.draft, view.isTyping, width) + buttonRowsOf(buttons, inner)
271}
272
hooks/project.ts 569 lines
1import type { Task, TaskRef, Took } from '../types'
2import { isShown } from './tasks'
3
4/** How often a live session says so in the project's store. */
5export const HEARTBEAT_MS = 60_000
6
7/** A session not heard from for this long is gone: its tasks are free to adopt. */
8export const STALE_MS = 3 * 60_000
9
10/** How long a note of tasks taken from a quiet session waits for it to come back. */
11export const TAKEN_MS = 30 * 24 * 60 * 60_000
12
13/**
14 * One session's part of a project: its tasks, when it was last alive, the
15 * next task number as it counts them, and the tasks it took on from others.
16 */
17export type Slot = {
18  tasks: Task[]
19  seenMs: number
20  /** Set when the session ended: its tasks wait for the next session here. */
21  endedMs?: number
22  /** Absent from a slot 0.1.4 wrote. */
23  nextId?: number
24  took?: Record<string, Took>
25}
26
27/** 0.1.4's note: the numbers of a quiet session's tasks another session took on. */
28export type Note = { ids: number[]; atMs: number }
29
30/**
31 * 0.1.4's layout: the whole project in one value, which each of its sessions
32 * reads and writes back whole. This version reads it, and changes it only
33 * where it takes on a 0.1.4 session's tasks.
34 */
35export type Legacy = { nextId: number; sessions: Record<string, Slot>; taken: Record<string, Note> }
36
37/**
38 * A project as the store holds it: each session's slot by session id, and
39 * 0.1.4's value. Gathered from them as read: every slot of both (a session in
40 * both writes its own key now), its notes less what was taken back since, and
41 * the tasks other sessions noted taking on from each, by its id.
42 */
43export type Project = {
44  slots: Record<string, Slot>
45  legacy: Legacy
46  all: Record<string, Slot>
47  tookFrom: Record<string, TaskRef[]>
48}
49
50/** A change to 0.1.4's value: slots taken out, notes left for their quiet sessions, and this session's note read. */
51export type LegacyEdit = { removed: string[]; taken: Record<string, Note>; read?: string }
52
53/** The store's longest key, in UTF-16 code units: the engine checks a key's `length`. */
54const MAX_KEY = 256
55
56/** Room kept in a session's key for its id, which is a UUID (36 characters). */
57const MAX_SESSION_ID = 64
58
59/**
60 * Where a project sits in the store. `$.store` writes one key at a time,
61 * under a lock, and has no compare-and-set: so each session's slot has a key
62 * of its own, which only that session writes, and no session's write can put
63 * back a stale copy of another's. A root too long for the store's keys goes
64 * by its hash. `legacy` is 0.1.4's key, absent when it is too long to read.
65 */
66export function keysOf(root: string) {
67  const legacy = `tasks:${root}`
68  const name = `${legacy}#session:`.length + MAX_SESSION_ID <= MAX_KEY ? root : `#${hashOf(root)}`
69  const prefix = `tasks:${name}#session:`
70
71  return {
72    legacy: legacy.length <= MAX_KEY ? legacy : undefined,
73    prefix,
74    session: (id: string) => `${prefix}${id}`,
75  }
76}
77
78/** 53 bits of `text`'s hash (cyrb53), in base 36. */
79function hashOf(text: string): string {
80  let h1 = 0xdeadbeef
81  let h2 = 0x41c6ce57
82
83  for (let i = 0; i < text.length; i++) {
84    const code = text.charCodeAt(i)
85    h1 = Math.imul(h1 ^ code, 2654435761)
86    h2 = Math.imul(h2 ^ code, 1597334677)
87  }
88
89  h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909)
90  h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909)
91
92  return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36)
93}
94
95/** Whether a stored value is an object with an array under `list` and a number under `count`: a slot's shape, and a note's. */
96function isShaped(value: unknown, list: string, count: string): value is Record<string, unknown> {
97  const record = value as Record<string, unknown> | null
98
99  return record !== null && typeof record === 'object' && Array.isArray(record[list]) && typeof record[count] === 'number'
100}
101
102/** Whether a stored value is a slot: anything else under a slot's key is skipped. */
103export function isSlot(value: unknown): value is Slot {
104  return isShaped(value, 'tasks', 'seenMs')
105}
106
107function isNote(value: unknown): value is Note {
108  return isShaped(value, 'ids', 'atMs')
109}
110
111/** Whether a stored value is a task, as the pane and the project's reckoning read one. */
112function isTask(value: unknown): value is Task {
113  const task = value as Record<string, unknown> | null
114  const isText = (key: string) => typeof task?.[key] === 'string'
115  const options = task?.['options']
116
117  return (
118    task !== null &&
119    typeof task === 'object' &&
120    ['id', 'createdMs', 'updatedMs'].every(key => typeof task[key] === 'number') &&
121    ['title', 'why', 'kind', 'state', 'update', 'sessionId'].every(isText) &&
122    ['doneWhen', 'answer', 'reason'].every(key => task[key] === undefined || isText(key)) &&
123    (options === undefined || (Array.isArray(options) && options.every(option => typeof option === 'string')))
124  )
125}
126
127function isRef(value: unknown): value is TaskRef {
128  const ref = value as Partial<TaskRef> | null
129
130  return ref !== null && typeof ref === 'object' && typeof ref.id === 'number' && typeof ref.createdMs === 'number'
131}
132
133/** The entries of a stored record as `of` reads them; one it reads as nothing is skipped. */
134function entriesOf<T>(raw: unknown, of: (value: unknown) => T | undefined): Record<string, T> {
135  const read: Record<string, T> = {}
136
137  for (const [key, value] of raw !== null && typeof raw === 'object' ? Object.entries(raw) : []) {
138    const entry = of(value)
139
140    if (entry !== undefined) {
141      read[key] = entry
142    }
143  }
144
145  return read
146}
147
148/** A stored value as a note of tasks taken, less what in it isn't one; nothing when it isn't a note. */
149function tookIn(value: unknown): Took | undefined {
150  if (!isShaped(value, 'tasks', 'atMs')) {
151    return undefined
152  }
153
154  return { tasks: (value.tasks as unknown[]).filter(isRef), atMs: value.atMs as number, ...(value.isEnded === true ? { isEnded: true } : {}) }
155}
156
157/** A stored value as a slot, less what in it isn't a task, a count or a note; nothing when it isn't a slot. */
158function slotIn(value: unknown): Slot | undefined {
159  if (!isSlot(value)) {
160    return undefined
161  }
162
163  return {
164    tasks: value.tasks.filter(isTask),
165    seenMs: value.seenMs,
166    ...(typeof value.endedMs === 'number' ? { endedMs: value.endedMs } : {}),
167    ...(typeof value.nextId === 'number' ? { nextId: value.nextId } : {}),
168    ...(value.took === undefined ? {} : { took: entriesOf(value.took, tookIn) }),
169  }
170}
171
172/** Reads 0.1.4's value, its first layout (one list for the project) included. */
173export function legacyOf(raw: unknown): Legacy {
174  const value = (raw ?? {}) as { nextId?: unknown; sessions?: unknown; tasks?: unknown; taken?: unknown }
175  const nextId = typeof value.nextId === 'number' ? value.nextId : 1
176  const taken = entriesOf(value.taken, note => (isNote(note) ? note : undefined))
177
178  if (value.sessions !== null && typeof value.sessions === 'object') {
179    return { nextId, sessions: entriesOf(value.sessions, slotIn), taken }
180  }
181
182  // The first layout kept one list per project: its tasks belong to sessions
183  // that have ended.
184  const sessions: Record<string, Slot> = {}
185
186  for (const task of Array.isArray(value.tasks) ? value.tasks.filter(isTask) : []) {
187    const slot = (sessions[task.sessionId] ??= { tasks: [], seenMs: 0, endedMs: 0 })
188    slot.tasks.push(task)
189  }
190
191  return { nextId, sessions, taken: {} }
192}
193
194/**
195 * A project from the store's values, by key. A session id has no `#`: a key
196 * past the prefix that has one is another root's, whose path goes on with
197 * `#session:`.
198 */
199export function projectOf(root: string, values: Readonly<Record<string, unknown>>): Project {
200  const keys = keysOf(root)
201  const slots: Record<string, Slot> = {}
202
203  for (const [key, value] of Object.entries(values)) {
204    const id = key.startsWith(keys.prefix) ? key.slice(keys.prefix.length) : '#'
205    const slot = id.includes('#') ? undefined : slotIn(value)
206
207    if (slot !== undefined) {
208      slots[id] = slot
209    }
210  }
211
212  return gathered(slots, legacyOf(keys.legacy === undefined ? undefined : values[keys.legacy]))
213}
214
215/**
216 * `project` with these sessions' slots as given: the process's own account
217 * of them, which the store may not have yet.
218 */
219export function withSlots(project: Project, slots: Readonly<Record<string, Slot>>): Project {
220  return gathered({ ...project.slots, ...slots }, project.legacy)
221}
222
223/** A project from its slots and 0.1.4's value, with what is gathered from them. */
224function gathered(slots: Record<string, Slot>, legacy: Legacy): Project {
225  const stored = { ...legacy.sessions, ...slots }
226  const all: Record<string, Slot> = {}
227  const tookFrom: Record<string, TaskRef[]> = {}
228
229  for (const [other, slot] of Object.entries(stored)) {
230    const notes = Object.entries(slot.took ?? {}).map(([id, note]) => [id, stillTaken(stored, other, id, note)] as const)
231    const took = slot.took === undefined ? undefined : Object.fromEntries(notes.filter(([, note]) => note.tasks.length > 0))
232    all[other] = took === undefined ? slot : { ...slot, took }
233
234    for (const [id, note] of Object.entries(took ?? {})) {
235      if (id !== other) {
236        tookFrom[id] = [...(tookFrom[id] ?? []), ...note.tasks]
237      }
238    }
239  }
240
241  return { slots, legacy, all, tookFrom }
242}
243
244/**
245 * `note`, of the tasks session `taker` took on from session `from`, less
246 * those `from` took back since: a session resumed after it ended, say, that
247 * takes its tasks back from a quiet one that had taken them. Its later note
248 * outweighs the older one, which the quiet one drops if it comes back.
249 */
250function stillTaken(all: Readonly<Record<string, Slot>>, taker: string, from: string, note: Took): Took {
251  const back = all[from]?.took?.[taker]
252
253  if (back === undefined || back.atMs <= note.atMs) {
254    return note
255  }
256
257  return { ...note, tasks: without(note.tasks, back.tasks) }
258}
259
260const refOf = (task: Task): TaskRef => ({ id: task.id, createdMs: task.createdMs })
261
262const isSameRef = (one: TaskRef, other: TaskRef) => one.id === other.id && one.createdMs === other.createdMs
263
264/** Whether `one` and `other` are one task: a number alone can name two, drawn by two sessions at once. */
265export const isSameTask = (one: Task, other: Task) => one.sessionId === other.sessionId && isSameRef(one, other)
266
267/** The refs of `refs` that `others` doesn't name. */
268const without = (refs: readonly TaskRef[], others: readonly TaskRef[]) => refs.filter(ref => !others.some(other => isSameRef(other, ref)))
269
270const isRefTo = (task: Task) => (ref: TaskRef) => isSameRef(ref, task)
271
272/**
273 * Whether another session took `task` on from session `id`: noted in the
274 * taker's slot, or in a 0.1.4 note, which names numbers only.
275 */
276export function isTakenFrom(project: Project, id: string, task: Task): boolean {
277  return project.legacy.taken[id]?.ids.includes(task.id) === true || project.tookFrom[id]?.some(isRefTo(task)) === true
278}
279
280/** The tasks in session `id`'s slot that no other session took on. */
281function heldIn(project: Project, id: string, slot: Slot): Task[] {
282  return slot.tasks.filter(task => isShown(task) && !isTakenFrom(project, id, task))
283}
284
285/** Whether a session's tasks are free for another to take on: it ended, or went quiet. */
286export function isGone(slot: Slot, nowMs: number): boolean {
287  return slot.endedMs !== undefined || nowMs - slot.seenMs > STALE_MS
288}
289
290/**
291 * The next task number: past every number a session of the project has
292 * drawn. Each slot carries its session's count, and a slot leaves the store
293 * only once a later one carries it, so this never goes back.
294 */
295export function floorOf(project: Project): number {
296  const slots = Object.values(project.all)
297
298  return Math.max(project.legacy.nextId, ...slots.map(slot => slot.nextId ?? 1), ...slots.flatMap(slot => slot.tasks.map(task => task.id + 1)))
299}
300
301/** Whether a 0.1.4 session other than `sessionId` is alive in the project: it reads 0.1.4's value only. */
302export function hasLegacyPeer(project: Project, sessionId: string, nowMs: number): boolean {
303  return Object.entries(project.legacy.sessions).some(([id, slot]) => id !== sessionId && !isGone(slot, nowMs))
304}
305
306/** How many tasks wait in the project's other live sessions. */
307export function elsewhereIn(project: Project, sessionId: string, nowMs: number): number {
308  return Object.entries(project.all)
309    .filter(([id, slot]) => id !== sessionId && !isGone(slot, nowMs))
310    .reduce((sum, [id, slot]) => sum + heldIn(project, id, slot).length, 0)
311}
312
313/** One note of what was taken from a session, from two: the tasks of both, the later time, ended only if both say so. */
314function merged(one: Took | undefined, other: Took): Took {
315  if (one === undefined) {
316    return other
317  }
318
319  const tasks = [...one.tasks, ...without(other.tasks, one.tasks)]
320  const isEnded = one.isEnded === true && other.isEnded === true
321
322  return { tasks, atMs: Math.max(one.atMs, other.atMs), ...(isEnded ? { isEnded } : {}) }
323}
324
325/**
326 * Carries a slot's notes of what its session took into `into`, but for a
327 * note of tasks taken from `sessionId`: those it holds itself again.
328 */
329function carry(into: Record<string, Took>, notes: Slot['took'], sessionId: string) {
330  for (const [from, note] of Object.entries(notes ?? {})) {
331    if (from !== sessionId) {
332      into[from] = merged(into[from], note)
333    }
334  }
335}
336
337/**
338 * The session's own leftovers in 0.1.4's value, to take out: its slot, from
339 * before a hot reload into this version, and a note another session left it.
340 */
341function ownLegacy(project: Project, sessionId: string): LegacyEdit {
342  return {
343    removed: sessionId in project.legacy.sessions ? [sessionId] : [],
344    taken: {},
345    ...(sessionId in project.legacy.taken ? { read: sessionId } : {}),
346  }
347}
348
349/**
350 * Takes a slot that leaves the store out of 0.1.4's value too, where a 0.1.4
351 * session's write put back the copy of it from before its session came to
352 * this version: with the slot gone, the copy would pass for it.
353 */
354function dropLegacyCopy(project: Project, id: string, legacy: LegacyEdit) {
355  if (id in project.legacy.sessions && !legacy.removed.includes(id)) {
356    legacy.removed.push(id)
357  }
358}
359
360/** What a session joining a project takes on, and what it leaves for the store to clean. */
361export type Adoption = {
362  /** Its own tasks (a resumed session) and those of sessions that ended or went quiet. */
363  adopted: Task[]
364  /** Those it numbered anew, another having drawn their numbers too: each as it was, with its new number. */
365  renumbered: { task: Task; id: number }[]
366  /**
367   * Its notes of what it took: each kept in its slot, so a crash anywhere
368   * after leaves no task twice. Until that write lands, a session it took
369   * from that comes back keeps the tasks too, and lets them go once it reads
370   * the note.
371   */
372  took: Record<string, Took>
373  nextId: number
374  /** This version's slots to remove once its own is written: ended, or holding nothing. */
375  removed: string[]
376  legacy: LegacyEdit
377}
378
379/**
380 * Takes on, for `sessionId`, its own slot (a resumed session) and every slot
381 * of a session that is gone. Live sessions keep theirs, and so does a quiet
382 * one with tasks: if it comes back, it reads the note and lets them go. An
383 * ended session's slot is removed once the taker's is written, its notes
384 * carried over; so is an empty slot, its count carried in the taker's. Each
385 * takes with it any copy of it that 0.1.4's value still has.
386 *
387 * Two sessions assigning at the same moment can draw one number (the store
388 * has no way to reserve one): where their tasks meet here, the session's own
389 * keep theirs, the numbers its Claude knows, then those of `holder`, the
390 * session whose tasks the process holds (the one it left with /clear or a
391 * resume in place), the numbers the user knows, and a later one gets a new one.
392 * So does one with a number in `known`, the session's own tasks that it is
393 * done with, in no slot, or in a 0.1.4 note of tasks taken from it: a copy
394 * of that note a 0.1.4 session's write puts back would take it again.
395 *
396 * A session taking the project on as it ends (`isEnding`) takes nothing from
397 * a quiet one, which may come back: the next session to start takes it on.
398 */
399export function adopt(project: Project, sessionId: string, nowMs: number, known: readonly number[] = [], isEnding = false, holder: string | null = null): Adoption {
400  const all = project.all
401  const rank = (id: string) => (id === sessionId ? 0 : id === holder ? 1 : 2)
402  const ids = Object.keys(all).sort((a, b) => rank(a) - rank(b))
403  const adopted: Task[] = []
404  const renumbered: Adoption['renumbered'] = []
405  const took: Record<string, Took> = {}
406  const removed: string[] = []
407  const legacy = ownLegacy(project, sessionId)
408  // A 0.1.4 note's numbers were drawn from the project's count: a new number is past them.
409  const drawn = [...known, ...(project.legacy.taken[sessionId]?.ids ?? [])]
410  let nextId = Math.max(floorOf(project), ...known.map(id => id + 1))
411
412  for (const id of ids) {
413    const slot = all[id]!
414
415    if (id !== sessionId && (!isGone(slot, nowMs) || (isEnding && slot.endedMs === undefined))) {
416      continue
417    }
418
419    const held = heldIn(project, id, slot)
420
421    for (const task of held) {
422      if (adopted.some(one => one.id === task.id) || drawn.includes(task.id)) {
423        renumbered.push({ task, id: nextId })
424        adopted.push({ ...task, id: nextId++ })
425      } else {
426        adopted.push(task)
427      }
428    }
429
430    if (id === sessionId) {
431      // Resumed: what it took before, it still holds.
432      carry(took, slot.took, sessionId)
433      continue
434    }
435
436    const isEnded = slot.endedMs !== undefined
437
438    if (held.length > 0) {
439      took[id] = merged(took[id], { tasks: held.map(refOf), atMs: nowMs, ...(isEnded ? { isEnded } : {}) })
440    }
441
442    if (id in project.slots) {
443      if (isEnded || slot.tasks.length === 0) {
444        removed.push(id)
445        carry(took, slot.took, sessionId)
446        dropLegacyCopy(project, id, legacy)
447      }
448
449      continue
450    }
451
452    // A 0.1.4 session's: out of its value, with a note it reads if it comes
453    // back. The note names every task it showed, not just those taken now:
454    // it reads no note of this version's, and one left by whoever took the
455    // rest may have gone with a 0.1.4 session's write.
456    legacy.removed.push(id)
457
458    if (!isEnded && slot.tasks.length > 0) {
459      legacy.taken[id] = { ids: slot.tasks.filter(isShown).map(task => task.id), atMs: nowMs }
460    }
461  }
462
463  adopted.sort((a, b) => a.id - b.id)
464
465  return { adopted, renumbered, took, nextId, removed, legacy }
466}
467
468/**
469 * Session `sessionId`'s notes of what it took, less those no longer needed:
470 * the session it took from let go of the tasks or took them back, or it
471 * ended and its slot is gone, or the note is a month old. A slot left
472 * behind (an ended session's, whose removal didn't happen, or a quiet one's
473 * that never came back in a month) is removed now, with any copy of it in
474 * 0.1.4's value, its note kept until it is gone and its own notes carried
475 * over; so are the session's own leftovers in 0.1.4's value.
476 */
477export function prune(
478  project: Project,
479  sessionId: string,
480  took: Readonly<Record<string, Took>>,
481  nowMs: number,
482): { took: Record<string, Took>; removed: string[]; legacy: LegacyEdit } {
483  const kept: Record<string, Took> = {}
484  const removed: string[] = []
485  const legacy = ownLegacy(project, sessionId)
486  const keep = (id: string, note: Took) => {
487    kept[id] = merged(kept[id], note)
488  }
489
490  for (const [id, mine] of Object.entries(took)) {
491    const note = stillTaken(project.all, sessionId, id, mine)
492    const slot = project.all[id]
493    const isExpired = nowMs - note.atMs > TAKEN_MS
494
495    if (note.tasks.length === 0) {
496      continue
497    }
498
499    if (slot === undefined) {
500      // A quiet session may come back with its tasks in memory: the note
501      // waits for it. Once its slot is gone, nothing tells whether it ended
502      // since: a process that goes on after /clear takes on what it held,
503      // but for what a note names.
504      if (note.isEnded !== true && !isExpired) {
505        keep(id, note)
506      }
507
508      continue
509    }
510
511    const has = (task: Task) => note.tasks.some(isRefTo(task))
512
513    if (slot.seenMs > note.atMs && !slot.tasks.some(has)) {
514      continue
515    }
516
517    if (slot.seenMs <= note.atMs && (note.isEnded === true || isExpired || !(id in project.slots))) {
518      if (id in project.slots) {
519        removed.push(id)
520        dropLegacyCopy(project, id, legacy)
521
522        // What it took on from others, it may hold yet: its notes go on here.
523        carry(kept, slot.took, sessionId)
524      } else {
525        legacy.removed.push(id)
526
527        if (note.isEnded !== true) {
528          legacy.taken[id] = { ids: note.tasks.map(ref => ref.id), atMs: note.atMs }
529        }
530      }
531
532      keep(id, note)
533      continue
534    }
535
536    if (!isExpired) {
537      keep(id, note)
538    }
539  }
540
541  return { took: kept, removed, legacy }
542}
543
544export function isEmptyEdit(edit: LegacyEdit): boolean {
545  return edit.removed.length === 0 && Object.keys(edit.taken).length === 0 && edit.read === undefined
546}
547
548/** `edit` applied to 0.1.4's value as it stands now, the count raised to `nextId`; notes a month old leave. */
549export function editedLegacy(current: Legacy, edit: LegacyEdit, nextId: number, nowMs: number): Legacy {
550  const sessions = { ...current.sessions }
551  const taken: Record<string, Note> = {}
552
553  for (const id of edit.removed) {
554    delete sessions[id]
555  }
556
557  for (const [id, note] of Object.entries(current.taken)) {
558    if (id !== edit.read && nowMs - note.atMs < TAKEN_MS) {
559      taken[id] = note
560    }
561  }
562
563  for (const [id, note] of Object.entries(edit.taken)) {
564    taken[id] = { ids: [...new Set([...(taken[id]?.ids ?? []), ...note.ids])], atMs: note.atMs }
565  }
566
567  return { nextId: Math.max(current.nextId, nextId), sessions, taken }
568}
569
hooks/text.ts 181 lines
1/** Collapses runs of whitespace, newlines included, to single spaces. */
2export function oneLine(text: string): string {
3  return text.replace(/\s+/g, ' ').trim()
4}
5
6/** Cuts `text` to `max` characters, marking the cut with an ellipsis. */
7export function clip(text: string, max: number): string {
8  return text.length > max ? `${text.slice(0, max - 1)}…` : text
9}
10
11/**
12 * A label safe to draw: control, format and line-separator characters out
13 * (the engine refuses a drawing holding one), whitespace collapsed, and cut
14 * to `max`. Titles and reasons are text the model or the user wrote.
15 */
16export function printable(text: string, max: number): string {
17  const spaced = text.replace(/[\p{Cc}\p{Zl}\p{Zp}]/gu, ' ').replace(/\p{Cf}/gu, '')
18
19  return clip(oneLine(spaced), max)
20}
21
22export function plural(count: number, word: string): string {
23  return `${count} ${word}${count === 1 ? '' : 's'}`
24}
25
26/** `#3, #5`: task numbers as a toast or a notice names them. */
27export function numbersOf(ids: readonly number[]): string {
28  return ids.map(id => `#${id}`).join(', ')
29}
30
31/** `now`, `4m`, `3h`, `2d`: how long ago, at a glance. */
32export function ago(ms: number): string {
33  const minutes = Math.floor(Math.max(0, ms) / 60_000)
34
35  if (minutes < 1) {
36    return 'now'
37  }
38
39  if (minutes < 60) {
40    return `${minutes}m`
41  }
42
43  const hours = Math.floor(minutes / 60)
44
45  return hours < 24 ? `${hours}h` : `${Math.floor(hours / 24)}d`
46}
47
48/** `840 B`, `2.3 KB`. */
49export function sizeOf(chars: number): string {
50  return chars < 1024 ? `${chars} B` : `${(chars / 1024).toFixed(1)} KB`
51}
52
53/**
54 * Wide in a terminal: East Asian wide and fullwidth forms, and emoji drawn
55 * as emoji by default (`⌚`, `✅`, `🀄`; `☀` asks for it with U+FE0F). A
56 * flag's two letters take a cell each.
57 */
58const WIDE =
59  /[\u1100-\u115F\u2329\u232A\u2630-\u2637\u268A-\u268F\u2E80-\u303E\u3041-\u3247\u3250-\u9FFF\uA000-\uA4CF\uA960-\uA97F\uAC00-\uD7A3\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE6B\uFF00-\uFF60\uFFE0-\uFFE6\u{16FE0}-\u{16FE3}\u{16FF0}-\u{16FF6}\u{17000}-\u{18DFF}\u{1AFF0}-\u{1B2FF}\u{1D300}-\u{1D376}\u{1F200}-\u{1F2FF}\u{20000}-\u{3FFFD}]|(?!\p{Regional_Indicator})\p{Emoji_Presentation}/u
60
61/** Drawn in no cell of its own: a mark or format character, a Hangul vowel or final joining its syllable. */
62const JOINING = /[\p{M}\p{Cf}\u1160-\u11FF\uD7B0-\uD7FF]/u
63
64/**
65 * The terminal cells `text` takes, as the engine counts them: two for a
66 * wide character, none for a mark on the one before, and two for an emoji
67 * however it is built (`☀️`, `1️⃣`, `1⃣`, `👍🏽`, `👩‍💻`, `❤‍🔥`).
68 */
69export function cellsOf(text: string): number {
70  let cells = 0
71  // The character the ones after it may join, and the cells they take together.
72  let base = ''
73  let width = 0
74  let previous = ''
75
76  for (const char of text) {
77    if (char === '\uFE0F' && width === 1 && /\p{Emoji}/u.test(base) && !/[0-9#*]/.test(base)) {
78      // A digit, `#` and `*` widen only in a keycap.
79      width = 2
80    } else if (char === '\u20E3') {
81      // A keycap, whatever it encloses.
82      width = 2
83    } else if (char === '\u200D' && width === 1 && /\p{Extended_Pictographic}/u.test(base) && !/[©®]/.test(base)) {
84      // An emoji drawn as text joining another draws as an emoji (`❤‍🔥`); the engine leaves `©` and `®`, the two below U+0100, as text.
85      width = 2
86    } else if (/\p{Emoji_Modifier}/u.test(char) && /\p{Emoji_Modifier_Base}/u.test(previous)) {
87      width = 2
88    } else if (previous === '\u200D' && width === 2 && /\p{Extended_Pictographic}/u.test(base) && /\p{Extended_Pictographic}/u.test(char)) {
89      // Joined by U+200D, emoji draw as one.
90    } else if (!JOINING.test(char)) {
91      cells += width
92      base = char
93      width = WIDE.test(char) ? 2 : 1
94    }
95
96    previous = char
97  }
98
99  return cells + width
100}
101
102/** Splits text into what the terminal draws as one: a character with its marks, joiners and modifiers. */
103const GRAPHEMES = new Intl.Segmenter(undefined, { granularity: 'grapheme' })
104
105/**
106 * The rows `text` takes in `columns` cells, wrapped as the terminal's `Text`
107 * with `wrap="wrap"` wraps it: at spaces, the space kept at the end of the
108 * row, and a word longer than a row broken where the row ends, between the
109 * characters it draws.
110 */
111export function wrapRows(text: string, columns: number): string[] {
112  const width = Math.max(1, Math.floor(columns))
113  const rows = ['']
114  // The cells the last row takes.
115  let used = 0
116
117  const breakRow = () => {
118    rows.push('')
119    used = 0
120  }
121
122  const add = (piece: string, cells: number) => {
123    rows[rows.length - 1] += piece
124    used += cells
125  }
126
127  text.split(' ').forEach((word, i) => {
128    if (i > 0) {
129      if (used >= width) {
130        breakRow()
131      }
132
133      add(' ', 1)
134    }
135
136    const length = cellsOf(word)
137
138    if (length > width) {
139      // A word wider than a row starts on this one when that breaks it no more often.
140      const breaksHere = 1 + Math.floor((length - (width - used) - 1) / width)
141      const breaksNext = Math.floor((length - 1) / width)
142
143      if (breaksNext < breaksHere) {
144        breakRow()
145      }
146
147      for (const { segment } of GRAPHEMES.segment(word)) {
148        const cells = cellsOf(segment)
149
150        // One wider than the row, after a full one, leaves a row empty between them.
151        if (used === width && cells > width) {
152          breakRow()
153        }
154
155        // One that doesn't fit breaks the row, an empty one too: the engine
156        // draws one wider than any row under an empty row.
157        if (used + cells > width) {
158          breakRow()
159        }
160
161        add(segment, cells)
162      }
163
164      return
165    }
166
167    if (used + length > width && used > 0 && length > 0) {
168      breakRow()
169    }
170
171    add(word, length)
172  })
173
174  return rows
175}
176
177/** How many rows `text` wraps to in `columns` cells. */
178export function rowsOf(text: string, columns: number): number {
179  return wrapRows(text, columns).length
180}
181
types/index.d.ts 80 lines
1/**
2 * What Claude needs from the user: something done (`do`), an answer in
3 * their own words (`answer`), or one of a few options (`choose`).
4 */
5export type TaskKind = 'do' | 'answer' | 'choose'
6
7/**
8 * Where a task stands: waiting for the user (`open`), fulfilled (`done`),
9 * turned down (`rejected`), or taken back by Claude (`withdrawn`).
10 */
11export type TaskState = 'open' | 'done' | 'rejected' | 'withdrawn'
12
13/**
14 * Whether Claude has heard of the user's latest move on the task: nothing
15 * to tell (`none`), told nothing yet (`pending`), or told (`delivered`).
16 */
17export type TaskUpdate = 'none' | 'pending' | 'delivered'
18
19/** A task Claude gave the user. */
20export type Task = {
21  /** Counts up per project: #1, #2, … */
22  id: number
23  title: string
24  why: string
25  doneWhen?: string
26  kind: TaskKind
27  options?: readonly string[]
28  state: TaskState
29  /** The user's answer, or the option they chose. */
30  answer?: string
31  /** Why the user rejected it, or why Claude withdrew it. */
32  reason?: string
33  update: TaskUpdate
34  /** The session that assigned it. */
35  sessionId: string
36  createdMs: number
37  updatedMs: number
38}
39
40/**
41 * A task as the session that held it numbered it, and when it was assigned:
42 * where two sessions drew one number, that tells their tasks apart.
43 */
44export type TaskRef = { id: number; createdMs: number }
45
46/**
47 * The tasks one session took on from another that had ended or gone quiet,
48 * as that session numbered them, and when. `isEnded`: it had ended, so it
49 * won't come back for them.
50 */
51export type Took = { tasks: readonly TaskRef[]; atMs: number; isEnded?: boolean }
52
53/**
54 * The selected task's field, when the pane shows one in place of its
55 * buttons: an answer, or a reason for rejecting. `held` is an answer held
56 * back because it looks like a secret.
57 */
58export type Editing = {
59  id: number
60  field: 'answer' | 'reason'
61  held?: string
62}
63
64declare module 'claude-code' {
65  interface PluginState {
66    'human-in-the-loop': {
67      tasks: readonly Task[]
68      nextId: number
69      /** The tasks this session took on from others, by their session id. */
70      took: Readonly<Record<string, Took>>
71      selectedId: number | null
72      editing: Editing | null
73      loadedFor: string | null
74      isWorking: boolean
75      /** The remote clients attached, by surface: two phones are two clients on one. */
76      clients: Readonly<Partial<Record<RenderSurface, readonly string[]>>>
77    }
78  }
79}
80