bom-pi 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/README.md +33 -2
  2. package/apps/README.md +7 -0
  3. package/apps/web/README.md +21 -0
  4. package/apps/web/pocket-adapter.mjs +323 -0
  5. package/apps/web/public/LICENSE.pocket +21 -0
  6. package/apps/web/public/activity-fold.js +28 -0
  7. package/apps/web/public/agent-now.js +37 -0
  8. package/apps/web/public/agent-tile.js +79 -0
  9. package/apps/web/public/app.js +975 -0
  10. package/apps/web/public/apple-touch-icon.png +0 -0
  11. package/apps/web/public/artifact-bridge.js +687 -0
  12. package/apps/web/public/avatar.js +87 -0
  13. package/apps/web/public/back.js +554 -0
  14. package/apps/web/public/box-keys.js +216 -0
  15. package/apps/web/public/browser-panel.js +1097 -0
  16. package/apps/web/public/browser.js +68 -0
  17. package/apps/web/public/calls.js +139 -0
  18. package/apps/web/public/chat.js +919 -0
  19. package/apps/web/public/clock.js +34 -0
  20. package/apps/web/public/commands.js +578 -0
  21. package/apps/web/public/composer.js +2068 -0
  22. package/apps/web/public/diff-parse.js +672 -0
  23. package/apps/web/public/diff.js +1646 -0
  24. package/apps/web/public/dock.js +299 -0
  25. package/apps/web/public/extension-ui.js +2734 -0
  26. package/apps/web/public/files-panel.js +775 -0
  27. package/apps/web/public/files.js +368 -0
  28. package/apps/web/public/fonts/FiraCode-VF.woff2 +0 -0
  29. package/apps/web/public/fonts/Geist.woff2 +0 -0
  30. package/apps/web/public/fonts/IBMPlexMono-Variable-Italic.woff2 +0 -0
  31. package/apps/web/public/fonts/IBMPlexMono-Variable.woff2 +0 -0
  32. package/apps/web/public/fonts/InterVariable-Italic.woff2 +0 -0
  33. package/apps/web/public/fonts/InterVariable.woff2 +0 -0
  34. package/apps/web/public/fonts/Iosevka-Bold.woff2 +0 -0
  35. package/apps/web/public/fonts/Iosevka-BoldItalic.woff2 +0 -0
  36. package/apps/web/public/fonts/Iosevka-Italic.woff2 +0 -0
  37. package/apps/web/public/fonts/Iosevka-Regular.woff2 +0 -0
  38. package/apps/web/public/fonts/Iosevka-SemiBold.woff2 +0 -0
  39. package/apps/web/public/fonts/Iosevka-SemiBoldItalic.woff2 +0 -0
  40. package/apps/web/public/fonts/JetBrainsMono-Italic.woff2 +0 -0
  41. package/apps/web/public/fonts/JetBrainsMono.woff2 +0 -0
  42. package/apps/web/public/fonts/NerdFontsSymbolsMono.woff2 +0 -0
  43. package/apps/web/public/fonts/SOURCES.md +69 -0
  44. package/apps/web/public/gestures.js +610 -0
  45. package/apps/web/public/highlight.js +480 -0
  46. package/apps/web/public/history.js +70 -0
  47. package/apps/web/public/home.js +169 -0
  48. package/apps/web/public/icon-192.png +0 -0
  49. package/apps/web/public/icon-512.png +0 -0
  50. package/apps/web/public/icon-maskable-512.png +0 -0
  51. package/apps/web/public/icon.svg +16 -0
  52. package/apps/web/public/index.html +71 -0
  53. package/apps/web/public/launcher.js +1293 -0
  54. package/apps/web/public/linked-sessions.js +55 -0
  55. package/apps/web/public/live.js +39 -0
  56. package/apps/web/public/manifest.webmanifest +32 -0
  57. package/apps/web/public/model-refresh.js +73 -0
  58. package/apps/web/public/notify.js +251 -0
  59. package/apps/web/public/peeks.js +920 -0
  60. package/apps/web/public/pip-attachments.js +182 -0
  61. package/apps/web/public/pip-window.js +141 -0
  62. package/apps/web/public/pip.js +1217 -0
  63. package/apps/web/public/quote-reply.js +109 -0
  64. package/apps/web/public/quote-text.js +31 -0
  65. package/apps/web/public/rich.js +403 -0
  66. package/apps/web/public/run-frame.js +106 -0
  67. package/apps/web/public/safe-mode.js +71 -0
  68. package/apps/web/public/seen.js +169 -0
  69. package/apps/web/public/session-tree.js +117 -0
  70. package/apps/web/public/sessions.js +2695 -0
  71. package/apps/web/public/share.js +126 -0
  72. package/apps/web/public/sheets/appearance.js +820 -0
  73. package/apps/web/public/sheets/branch.js +353 -0
  74. package/apps/web/public/sheets/extensions.js +818 -0
  75. package/apps/web/public/sheets/file.js +318 -0
  76. package/apps/web/public/sheets/find.js +250 -0
  77. package/apps/web/public/sheets/folder.js +680 -0
  78. package/apps/web/public/sheets/gallery.js +2340 -0
  79. package/apps/web/public/sheets/hooks.js +350 -0
  80. package/apps/web/public/sheets/memory.js +531 -0
  81. package/apps/web/public/sheets/menu.js +580 -0
  82. package/apps/web/public/sheets/message.js +220 -0
  83. package/apps/web/public/sheets/model.js +412 -0
  84. package/apps/web/public/sheets/people.js +414 -0
  85. package/apps/web/public/sheets/pi-sessions.js +264 -0
  86. package/apps/web/public/sheets/providers.js +525 -0
  87. package/apps/web/public/sheets/running.js +130 -0
  88. package/apps/web/public/sheets/schedules.js +71 -0
  89. package/apps/web/public/sheets/session.js +249 -0
  90. package/apps/web/public/sheets/shortcuts.js +101 -0
  91. package/apps/web/public/sheets/spend.js +150 -0
  92. package/apps/web/public/sheets/text.js +53 -0
  93. package/apps/web/public/sheets/viewers.js +363 -0
  94. package/apps/web/public/sheets/worktree.js +50 -0
  95. package/apps/web/public/sheets.js +410 -0
  96. package/apps/web/public/signin.js +57 -0
  97. package/apps/web/public/slots.js +208 -0
  98. package/apps/web/public/store.js +1760 -0
  99. package/apps/web/public/style.css +18625 -0
  100. package/apps/web/public/subagents-board.js +879 -0
  101. package/apps/web/public/subagents.js +273 -0
  102. package/apps/web/public/sw.js +169 -0
  103. package/apps/web/public/taps.js +26 -0
  104. package/apps/web/public/theme-surface.d.ts +4 -0
  105. package/apps/web/public/theme-surface.js +266 -0
  106. package/apps/web/public/theme.js +845 -0
  107. package/apps/web/public/themes/lantern/colors.toml +25 -0
  108. package/apps/web/public/themes/lantern/direction.css +60 -0
  109. package/apps/web/public/themes/lantern/frame.css +254 -0
  110. package/apps/web/public/themes/lantern/theme.css +10 -0
  111. package/apps/web/public/themes/lantern/theme.json +7 -0
  112. package/apps/web/public/themes/pocket/theme.css +189 -0
  113. package/apps/web/public/themes/pocket/theme.json +6 -0
  114. package/apps/web/public/themes.js +556 -0
  115. package/apps/web/public/transcript.js +3348 -0
  116. package/apps/web/public/trust.js +295 -0
  117. package/apps/web/public/turns.js +507 -0
  118. package/apps/web/public/ui.js +1910 -0
  119. package/apps/web/public/voice.js +345 -0
  120. package/apps/web/server.mjs +774 -0
  121. package/package.json +43 -4
  122. package/packages/cli/src/bom-pi.mjs +452 -0
  123. package/packages/cli/templates/blank.factory.json +7 -0
  124. package/packages/cli/templates/dev.factory.json +11 -0
  125. package/packages/cli/templates/docs.factory.json +12 -0
  126. package/packages/cli/templates/ops.factory.json +14 -0
  127. package/packages/cli/templates/triage.factory.json +10 -0
  128. package/packages/core/src/daemon.mjs +2047 -0
  129. package/packages/core/src/limit-gate.mjs +192 -0
  130. package/packages/core/src/rpc-client.mjs +66 -0
  131. package/systemd/README.md +11 -0
@@ -0,0 +1,2068 @@
1
+ // The message box: send, steer or queue while busy, attach files, mention files with @, run commands with !, recall
2
+ // what was sent before (↑, Ctrl+R), fold long pastes, pick the model, stop.
3
+ import { useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
4
+ import { Avatar } from "./avatar.js";
5
+ import { boxKey, keyBox } from "./box-keys.js";
6
+ import { chatUnread, TypingLine } from "./chat.js";
7
+ import {
8
+ loadTemplates,
9
+ parseCommand,
10
+ parseTemplate,
11
+ planAvailable,
12
+ suggestCommands,
13
+ } from "./commands.js";
14
+ import { withQuote } from "./quote-text.js";
15
+ import { loadFiles, mentionAt, mentionText, suggestFiles } from "./files.js";
16
+ import { remember, searchHistory, sentHistory } from "./history.js";
17
+ import {
18
+ actions,
19
+ attempt,
20
+ canSteer,
21
+ collab,
22
+ drafts,
23
+ navigate,
24
+ notify,
25
+ openSheet,
26
+ store,
27
+ typing,
28
+ uid,
29
+ } from "./store.js";
30
+ import { useDock } from "./dock.js";
31
+ import { defineItem, slotItems } from "./slots.js";
32
+ import { SubagentsBar } from "./subagents.js";
33
+ import { TrustBar } from "./trust.js";
34
+ import { prefs } from "./theme.js";
35
+ import { says } from "./turns.js";
36
+ import { MicButton, useDictation } from "./voice.js";
37
+ import {
38
+ APPLE,
39
+ contextLevel,
40
+ fileUrl,
41
+ formatBytes,
42
+ formatTokens,
43
+ html,
44
+ Icon,
45
+ Marked,
46
+ modelLabel,
47
+ Spinner,
48
+ } from "./ui.js";
49
+
50
+ /** The explicit route to the parent on every layout, outside the dock and the scrolling conversation. */
51
+ function ParentSessionButton() {
52
+ const parent = store.state.view.conversation?.parent;
53
+
54
+ if (!parent) {
55
+ return null;
56
+ }
57
+
58
+ return html`<button
59
+ class="parent-session"
60
+ aria-label=${`Back to main session: ${parent.title}`}
61
+ title=${`Return to ${parent.title}`}
62
+ onClick=${() => navigate(parent.id)}
63
+ >
64
+ <${Icon} name="back" size=${16} />
65
+ <span>Back to main session</span>
66
+ <span class="parent-session-title">${parent.title}</span>
67
+ </button>`;
68
+ }
69
+
70
+ const coarse = matchMedia("(pointer: coarse)").matches;
71
+ /**
72
+ * A session opened by an Alt shortcut on an Apple keyboard, whose message box leaves the focus where it is: Option types
73
+ * characters in a box, where the app's Alt shortcuts do nothing, so the next Alt+1…9 would type ™ there instead.
74
+ */
75
+ let openedByAlt = null;
76
+
77
+ export const openingByAlt = (id) => (openedByAlt = APPLE ? id : null);
78
+ /** The newest "Send to Pi" text already put into a message box (see `insertIntoComposer`). */
79
+ let insertedUpTo = 0;
80
+
81
+ /** Pasted text this long goes into the box as a placeholder; the message goes out with the text in its place. */
82
+ const PASTE_LINES = 20;
83
+ const PASTE_CHARS = 2000;
84
+ const PASTED = /\[Pasted text #(\d+)[^\]\n]*\]/g;
85
+ /** Sent messages longer than this are not kept for ↑: a long paste would crowd out the rest. */
86
+ const REMEMBER_CHARS = 20_000;
87
+ /** An @mention of a file (with a dot or a slash, unlike a person's name), for the Send files chip. */
88
+ const MENTIONS_FILE = /(?:^|[\s([{])@(?:"[^"\n]+"|[^\s"]*[./][^\s"]*)/;
89
+ const INLINE_KEY = "pocket.inlineFiles";
90
+
91
+ const pasteKey = (id) => `pocket.pastes.${id ?? "home"}`;
92
+
93
+ /** Each conversation's pastes by number, kept with its draft so a reload keeps them. */
94
+ function loadPastes(id) {
95
+ try {
96
+ return JSON.parse(localStorage.getItem(pasteKey(id)) ?? "{}");
97
+ } catch {
98
+ return {};
99
+ }
100
+ }
101
+
102
+ function savePastes(id, pastes) {
103
+ try {
104
+ if (Object.keys(pastes).length === 0) {
105
+ localStorage.removeItem(pasteKey(id));
106
+ } else {
107
+ localStorage.setItem(pasteKey(id), JSON.stringify(pastes));
108
+ }
109
+ } catch {
110
+ notify("warning", "This browser has no room to keep the paste after a reload.");
111
+ }
112
+ }
113
+
114
+ /** The message with each paste's placeholder replaced by what was pasted. */
115
+ const expandPastes = (text, pastes) => text.replace(PASTED, (whole, n) => pastes[n] ?? whole);
116
+
117
+ /**
118
+ * The subagents a waiting message carries reports from (`extensions/subagents.ts`), as the server reads them from its
119
+ * whole text: the queue gets only the start. Null for any other message, such as a person's, which has who sent it.
120
+ */
121
+ const queuedReports = (item) => item.reports ?? null;
122
+
123
+ /** How a message can go while Pi works: the value the server takes, its label, and what it does. */
124
+ const SEND_MODES = [
125
+ ["steer", "Steer", "Pi reads it now, between steps"],
126
+ ["followUp", "Queue", "Pi reads it when this run ends"],
127
+ [
128
+ "interrupt",
129
+ "Interrupt",
130
+ "Stops the run right now (also its tool call) and clears the queue, then sends it",
131
+ ],
132
+ ];
133
+
134
+ /** What a send mode does, for a queued message's buttons. */
135
+ const modeHint = (mode) => SEND_MODES.find(([value]) => value === mode)[2];
136
+
137
+ /** What Interrupt does to a message waiting in the queue: the others there stay, unlike the composer's Interrupt. */
138
+ const QUEUED_INTERRUPT_HINT =
139
+ "Stops the run right now (also its tool call), then sends this one. The other queued messages stay queued";
140
+
141
+ /**
142
+ * Whether a queued message's Interrupt asks first: the first tap reads "Interrupt?", a second within 4 s sends it.
143
+ * Set to false to send it on the first tap.
144
+ */
145
+ const CONFIRM_INTERRUPT = true;
146
+
147
+ /** What kind of message waits for Pi: a steer, one queued for after its answer, a note, or subagents' reports. */
148
+ function queuedMode(item) {
149
+ const names = queuedReports(item);
150
+
151
+ if (names) {
152
+ return names.length === 1 ? "Report" : "Reports";
153
+ }
154
+
155
+ return item.mode === "steer" ? "Steer" : item.mode === "followUp" ? "Queue" : "Note";
156
+ }
157
+
158
+ /** Who sent a message, as the server writes it at the start when several people use Pi (`FROM_PREFIX`). */
159
+ const FROM = /^\[from: [^\]\n]{1,60}\] /;
160
+
161
+ /** What a waiting message says (its row names who sent it); subagents' reports say whose, as their text is long. */
162
+ function queuedText(item) {
163
+ const names = queuedReports(item);
164
+
165
+ if (!names) {
166
+ return (item.text ?? "").replace(FROM, "");
167
+ }
168
+
169
+ return `from ${names.join(", ")}, on ${names.length === 1 ? "its" : "their"} way to Pi`;
170
+ }
171
+
172
+ /** Take turns: who drives, who asked, and the buttons to hand over, ask, or take the wheel. */
173
+ function DriverBar() {
174
+ const { view, me, users, presence } = store.state;
175
+ const turns = view.turns;
176
+ const [handing, setHanding] = useState(false);
177
+
178
+ if (!turns?.on) {
179
+ return null;
180
+ }
181
+
182
+ const name = (id) => users.find((user) => user.id === id)?.name ?? "someone";
183
+ const driving = turns.driver === me?.id;
184
+ const driverHere =
185
+ turns.driver !== undefined && presence.some((person) => person.id === turns.driver);
186
+ const run = (action, to) =>
187
+ attempt(() => actions.turns(action, to)).then(() => setHanding(false));
188
+
189
+ if (driving) {
190
+ const others = presence.filter(
191
+ (person) => person.id !== me?.id && person.role !== "viewer",
192
+ );
193
+
194
+ return html`<div class="driver-bar mine">
195
+ <span class="driver-label"><${Icon} name="wheel" size=${14} /> You're driving</span>
196
+ ${turns.asks.map(
197
+ (id) => html`<span class="driver-ask">
198
+ ${name(id)} asks to drive <button class="link small" onClick=${() => run("handover", id)}>Hand over</button>
199
+ </span>`,
200
+ )}
201
+ <span class="grow"></span>
202
+ ${
203
+ others.length > 0 &&
204
+ html`<button class="link small" onClick=${() => setHanding(!handing)}>
205
+ Hand over…
206
+ </button>`
207
+ }
208
+ <button class="link small" onClick=${() => run("release")}>Let go</button>
209
+ ${
210
+ handing &&
211
+ html`<div class="driver-pick">
212
+ ${others.map(
213
+ (person) => html`<button
214
+ class="chip"
215
+ onClick=${() => run("handover", person.id)}
216
+ >
217
+ <${Avatar} person=${person} size=${16} /> ${person.name}
218
+ </button>`,
219
+ )}
220
+ </div>`
221
+ }
222
+ </div>`;
223
+ }
224
+
225
+ const asked = turns.asks.includes(me?.id);
226
+ const canTake = !driverHere || me?.role === "owner";
227
+
228
+ return html`<div class="driver-bar">
229
+ <span class="driver-label">
230
+ <${Icon} name="wheel" size=${14} />
231
+ ${turns.driver === undefined ? "No one is driving" : `${name(turns.driver)} is driving${driverHere ? "" : " (away)"}`}
232
+ </span>
233
+ <span class="grow"></span>
234
+ ${
235
+ turns.driver !== undefined &&
236
+ driverHere &&
237
+ html`<button class="button small" disabled=${asked} onClick=${() => run("ask")}>
238
+ ${asked ? "Asked ✓" : "Ask to drive"}
239
+ </button>`
240
+ }
241
+ ${
242
+ canTake &&
243
+ html`<button class="button small primary" onClick=${() => run("claim")}>
244
+ Take the wheel
245
+ </button>`
246
+ }
247
+ </div>`;
248
+ }
249
+
250
+ /** Plan mode: Pi proposes and changes nothing until someone here approves its plan. */
251
+ function PlanBar({ blocked }) {
252
+ const { view } = store.state;
253
+
254
+ if (!view.plan?.on || !planAvailable()) {
255
+ return null;
256
+ }
257
+
258
+ // A subagent follows its session's plan mode; it is approved there.
259
+ const subagent = view.conversation?.kind === "subagent";
260
+ // There is a plan to approve once Pi has answered since plan mode went on.
261
+ const proposed =
262
+ view.plan.at === undefined ||
263
+ [...view.entries.values()].some(
264
+ (entry) =>
265
+ entry.kind === "assistant" &&
266
+ entry.at > view.plan.at &&
267
+ entry.stopReason !== "toolUse" &&
268
+ entry.blocks.some(says),
269
+ );
270
+
271
+ return html`<div class="plan-bar">
272
+ <span class="grow">
273
+ <strong>Plan mode.</strong> ${subagent ? "This subagent follows its session: it reads, and changes nothing." : "Pi reads and proposes; nothing changes until you approve."}
274
+ </span>
275
+ ${
276
+ !blocked &&
277
+ !subagent &&
278
+ html`<button class="link small" onClick=${() => attempt(() => actions.setPlan(false))}>
279
+ Turn off
280
+ </button>
281
+ <button
282
+ class="button small primary"
283
+ disabled=${view.live.busy || !proposed}
284
+ title=${proposed ? undefined : "Pi has not proposed a plan yet."}
285
+ onClick=${() => attempt(actions.approvePlan)}
286
+ >
287
+ Approve plan
288
+ </button>`
289
+ }
290
+ </div>`;
291
+ }
292
+
293
+ /** Done when: the check Pi works toward, how many checks it took, and a way to drop it. */
294
+ function GoalBar() {
295
+ const { goal } = store.state.view;
296
+
297
+ if (!goal) {
298
+ return null;
299
+ }
300
+
301
+ const command = html`<span class="mono">${goal.command}</span>`;
302
+ const text =
303
+ goal.status === "met"
304
+ ? html`<strong>Done:</strong> ${command} passes (check ${goal.tries} of ${goal.max}).`
305
+ : goal.status === "gave-up"
306
+ ? html`<strong>Stopped:</strong> ${command} still fails after ${goal.max} checks.`
307
+ : html`<strong>Until</strong> ${command} passes${goal.tries > 0 ? ` · check ${goal.tries} of ${goal.max} failed` : ""}.`;
308
+
309
+ return html`<div class=${`goal-bar ${goal.status}`}>
310
+ <span class="grow">${text}</span>
311
+ ${
312
+ canSteer() &&
313
+ html`<button class="link small" onClick=${() => attempt(actions.clearGoal)}>
314
+ ${goal.status === "working" ? "Drop" : "Dismiss"}
315
+ </button>`
316
+ }
317
+ </div>`;
318
+ }
319
+
320
+ /** How a watch's last look found the PR's checks, and why a watch ended. */
321
+ const WATCH_CHECKS = {
322
+ pending: "checks running",
323
+ passed: "checks pass",
324
+ failed: "checks failed",
325
+ };
326
+
327
+ function watchEnded(watch) {
328
+ switch (watch.status) {
329
+ case "merged":
330
+ return "was merged.";
331
+ case "closed":
332
+ return "was closed.";
333
+ case "gave-up":
334
+ return `had more to tell than ${watch.max} messages: watch stopped.`;
335
+ case "expired":
336
+ return "had nothing new for two weeks: watch stopped.";
337
+ default:
338
+ return `could not be watched: ${watch.note ?? "something went wrong"}.`;
339
+ }
340
+ }
341
+
342
+ /** A PR watch: which PR, its checks, what it sent Pi; stop it, or dismiss one that ended. */
343
+ function WatchBar() {
344
+ const { watch } = store.state.view;
345
+
346
+ if (!watch) {
347
+ return null;
348
+ }
349
+
350
+ const pr = html`<a href=${watch.url} target="_blank" rel="noopener">PR #${watch.number}</a>`;
351
+ const checks = WATCH_CHECKS[watch.checks];
352
+ const text =
353
+ watch.status === "watching"
354
+ ? html`<strong>Watching</strong> ${pr}${checks ? ` · ${checks}` : ""}${watch.sent > 0 ? ` · ${watch.sent} of ${watch.max} sent` : ""}${watch.unchecked ? " · owner's comments only" : ""}${watch.errors > 0 ? " · last look failed" : watch.note ? " · waiting" : ""}`
355
+ : html`${pr} ${watchEnded(watch)}`;
356
+
357
+ return html`<div
358
+ class=${`watch-bar ${watch.status}`}
359
+ title=${[
360
+ watch.title,
361
+ watch.unchecked &&
362
+ "Only the repository owner's comments count: gh cannot push there, so GitHub does not say who else can write.",
363
+ watch.note,
364
+ ]
365
+ .filter(Boolean)
366
+ .join("\n")}
367
+ >
368
+ <span class="grow">${text}</span>
369
+ ${
370
+ canSteer() &&
371
+ html`<button class="link small" onClick=${() => attempt(actions.unwatchPr)}>
372
+ ${watch.status === "watching" ? "Stop" : "Dismiss"}
373
+ </button>`
374
+ }
375
+ </div>`;
376
+ }
377
+
378
+ export function Composer() {
379
+ const { view, conversationId } = store.state;
380
+ const historyScope = { person: store.state.me?.id, conversation: conversationId };
381
+ const [text, setText] = useState(() => drafts.get(conversationId));
382
+ const [files, setFiles] = useState([]);
383
+ // How a message goes while Pi works: "steer", "followUp" (Queue), or "interrupt" (stop the run, then send).
384
+ const [sendMode, setSendMode] = useState("steer");
385
+ // The queued message tapped open, wrapped: one line each until then. The queue holds only a message's start.
386
+ const [reading, setReading] = useState(null);
387
+ // The queued message whose Interrupt was tapped once (`CONFIRM_INTERRUPT`).
388
+ const [interrupting, setInterrupting] = useState(null);
389
+ const [sending, setSending] = useState(false);
390
+ // Slash command suggestions: the highlighted one, and whether Escape hid the list.
391
+ const [pick, setPick] = useState(0);
392
+ const [hideCommands, setHideCommands] = useState(false);
393
+ // File mentions: where the caret is, and the mention Escape hid (by where it starts).
394
+ const [caret, setCaret] = useState(() => drafts.get(conversationId).length);
395
+ const [hiddenMention, setHiddenMention] = useState(null);
396
+ const [pastes, setPastes] = useState(() => loadPastes(conversationId));
397
+ // ↑ through what was sent before: where in that list, and the draft ↓ comes back to. Ctrl+R searches it.
398
+ const [browsing, setBrowsing] = useState(null);
399
+ const [searching, setSearching] = useState(false);
400
+ const [inlineFiles, setInlineFiles] = useState(() => localStorage.getItem(INLINE_KEY) === "1");
401
+ const box = useRef(null);
402
+ // The box as it comes and goes (taking the wheel shows it, with the draft in it): fitted to its text at once, and
403
+ // again when its width changes, which can come after the window's resize (the Peek column becoming a strip).
404
+ const [setBox] = useState(() => {
405
+ let width = -1;
406
+ // A new width only (fitting changes the box's height, which this hears too), fitted a frame later.
407
+ const observer = new ResizeObserver(([entry]) => {
408
+ if (entry.contentRect.width !== width) {
409
+ width = entry.contentRect.width;
410
+ requestAnimationFrame(() => fitBox(box.current));
411
+ }
412
+ });
413
+
414
+ return (element) => {
415
+ box.current = element;
416
+ // A frame later, not now: measuring in the middle of a render lays the whole page out early, and again for
417
+ // the frame, which on a phone made opening a session freeze longer. Still before the frame is painted.
418
+ requestAnimationFrame(() => fitBox(element));
419
+ observer.disconnect();
420
+ width = -1;
421
+
422
+ if (element) {
423
+ observer.observe(element);
424
+ }
425
+ };
426
+ });
427
+ // Dictation writes into the box as typing does, so the draft keeps what was heard.
428
+ const dictation = useDictation(box, (value, at) => {
429
+ setBrowsing(null);
430
+ update(value, at);
431
+ });
432
+ // What is above the message box, and how it shares the room with the conversation (`dock.js`).
433
+ const dock = useRef(null);
434
+ const picker = useRef(null);
435
+ const list = useRef(null);
436
+ // One per `!` command: sending it again after a lost reply runs it once. Made when the first is sent, not on each
437
+ // draw of the message box.
438
+ const requestId = useRef(null);
439
+ // An extension's command while its send is unresolved: sending the same text again finds the first run.
440
+ const commandRequest = useRef(null);
441
+ const busy = view.live.busy;
442
+ const agent = view.agent;
443
+
444
+ // An Interrupt is for the run it was chosen in: when Pi stops working, an unused one goes back to Steer, so it does
445
+ // not stop the next run. Steer and Queue stay as the person chose.
446
+ useEffect(() => {
447
+ if (!busy) {
448
+ setSendMode((mode) => (mode === "interrupt" ? "steer" : mode));
449
+ }
450
+ }, [busy]);
451
+ // A queued message's Interrupt asks for a second tap for a few seconds only, as Undo in a diff does.
452
+ useEffect(() => {
453
+ if (interrupting === null) {
454
+ return;
455
+ }
456
+
457
+ const timer = setTimeout(() => setInterrupting(null), 4000);
458
+
459
+ return () => clearTimeout(timer);
460
+ }, [interrupting]);
461
+ useEffect(() => {
462
+ const draft = drafts.get(conversationId);
463
+
464
+ dictation.stop(true);
465
+ setText(draft);
466
+ setCaret(draft.length);
467
+ setPastes(loadPastes(conversationId));
468
+ setBrowsing(null);
469
+ setSearching(false);
470
+ }, [conversationId]);
471
+ // A session opens with the caret in its message box, ready to type: not on a touch screen, where the keyboard would
472
+ // come up over the conversation, nor after an Alt shortcut on an Apple keyboard (`openingByAlt`), nor while another
473
+ // text field has the focus (the docked chat a mention opened, the session search): words typed there stay there.
474
+ useEffect(() => {
475
+ const byAlt = openedByAlt === conversationId;
476
+ const active = document.activeElement;
477
+ const typingElsewhere =
478
+ active instanceof HTMLElement &&
479
+ active !== box.current &&
480
+ (active.isContentEditable || /^(INPUT|TEXTAREA)$/.test(active.tagName));
481
+
482
+ openedByAlt = null;
483
+
484
+ if (!coarse && !byAlt && !typingElsewhere) {
485
+ box.current?.focus({ preventScroll: true });
486
+ }
487
+ }, []);
488
+ // Text sent here from the chat, the notes ("Send to Pi"), or another app (Share) goes after whatever is in the box,
489
+ // once: the message box is made again for every session, and must not add the same text there. Shared files are
490
+ // attached the same way.
491
+ const insert = store.state.composerInsert;
492
+
493
+ useEffect(() => {
494
+ if (!insert || insert.n <= insertedUpTo) {
495
+ return;
496
+ }
497
+
498
+ insertedUpTo = insert.n;
499
+
500
+ if (insert.files?.length > 0) {
501
+ addFiles(insert.files);
502
+ }
503
+
504
+ if (insert.text === "") {
505
+ return;
506
+ }
507
+
508
+ const current = drafts.get(conversationId);
509
+
510
+ update(
511
+ current.trim() === ""
512
+ ? insert.text
513
+ : `${current.replace(/\s+$/, "")}${insert.inline ? " " : "\n\n"}${insert.text}`,
514
+ );
515
+ requestAnimationFrame(() => {
516
+ const element = box.current;
517
+
518
+ if (!element) {
519
+ return;
520
+ }
521
+
522
+ element.focus();
523
+ element.setSelectionRange(element.value.length, element.value.length);
524
+ });
525
+ }, [insert?.n]);
526
+ useEffect(() => {
527
+ const fit = () => fitBox(box.current);
528
+
529
+ fit();
530
+ addEventListener("resize", fit);
531
+ // A theme's font wraps the text another way, once its stylesheets or the font itself have loaded.
532
+ document.addEventListener("pocket:theme", fit);
533
+ document.fonts?.addEventListener("loadingdone", fit);
534
+
535
+ return () => {
536
+ removeEventListener("resize", fit);
537
+ document.removeEventListener("pocket:theme", fit);
538
+ document.fonts?.removeEventListener("loadingdone", fit);
539
+ };
540
+ }, [text]);
541
+
542
+ const update = (value, at = value.length) => {
543
+ setText(value);
544
+ setCaret(at);
545
+ drafts.set(conversationId, value);
546
+ setPick(0);
547
+
548
+ if (!value.startsWith("/") || value === "/") {
549
+ setHideCommands(false);
550
+ }
551
+
552
+ if (value.startsWith("/")) {
553
+ loadTemplates();
554
+ }
555
+
556
+ // A command is not a message to Pi: no "typing to Pi" for it.
557
+ typing(value.trim() === "" || value.startsWith("/") ? null : "pi");
558
+ };
559
+
560
+ // Ctrl+R: what was sent before that has the words in the box.
561
+ const recalled = searching ? searchHistory(text, historyScope) : [];
562
+ const chosenRecall = recalled[Math.min(pick, recalled.length - 1)];
563
+ const suggestions = hideCommands || searching ? [] : suggestCommands(text);
564
+ const chosen = suggestions[Math.min(pick, suggestions.length - 1)];
565
+ const parsed = parseCommand(text);
566
+ const template = parsed ? null : parseTemplate(text);
567
+ // `!command` runs in the session's folder and Pi sees it; `!!command`, only the people here.
568
+ const shell = text.startsWith("!")
569
+ ? { context: !text.startsWith("!!"), command: text.replace(/^!!?/, "").trim() }
570
+ : null;
571
+ const mentionsFiles = !shell && !parsed && MENTIONS_FILE.test(text);
572
+ const pasted = PASTED.test(text);
573
+
574
+ PASTED.lastIndex = 0;
575
+ // The @path being typed at the caret, and the files that match it. Slash command names come first.
576
+ const typed = suggestions.length === 0 && !searching && !shell ? mentionAt(text, caret) : null;
577
+ const mention = typed && typed.start !== hiddenMention ? typed : null;
578
+ const found = mention ? suggestFiles(mention.query) : null;
579
+ const matches = found?.items ?? [];
580
+ const chosenFile = matches[Math.min(pick, matches.length - 1)];
581
+
582
+ // A new mention checks the folder's list again, in the background; a hidden one shows again once it is gone.
583
+ useEffect(() => {
584
+ if (mention) {
585
+ loadFiles();
586
+ }
587
+ }, [mention?.start, conversationId]);
588
+ useEffect(() => {
589
+ if (!typed && hiddenMention !== null) {
590
+ setHiddenMention(null);
591
+ }
592
+ }, [typed === null]);
593
+ // Arrowing through a long list keeps the highlighted one in view.
594
+ useEffect(
595
+ () => list.current?.querySelector(".command.on")?.scrollIntoView({ block: "nearest" }),
596
+ [pick],
597
+ );
598
+
599
+ const focusEnd = () =>
600
+ requestAnimationFrame(() => {
601
+ const element = box.current;
602
+
603
+ if (!element) {
604
+ return;
605
+ }
606
+
607
+ element.focus();
608
+ element.setSelectionRange(element.value.length, element.value.length);
609
+ });
610
+
611
+ /** Run a slash command. The text goes away once it worked; attached files stay for the next message. */
612
+ const runCommand = async ({ command, arg }, sent) => {
613
+ let request = null;
614
+
615
+ if (command.extension) {
616
+ const kept = commandRequest.current;
617
+
618
+ request =
619
+ kept?.commandId === command.id &&
620
+ kept.text === sent &&
621
+ kept.conversationId === conversationId
622
+ ? kept
623
+ : { requestId: uid(), commandId: command.id, text: sent, conversationId };
624
+ commandRequest.current = request;
625
+ }
626
+
627
+ setSending(true);
628
+ const ok = await attempt(async () => {
629
+ try {
630
+ await command.run(arg, request?.requestId);
631
+ } catch (error) {
632
+ // A 4xx made no run, or refused it for good: the next send is a new request. After a network error
633
+ // or a 5xx, the run may be there: the same send finds it.
634
+ if (error.status >= 400 && error.status < 500) {
635
+ commandRequest.current = null;
636
+ }
637
+
638
+ throw error;
639
+ }
640
+
641
+ return true;
642
+ });
643
+
644
+ setSending(false);
645
+
646
+ if (ok) {
647
+ commandRequest.current = null;
648
+ update("");
649
+ }
650
+ };
651
+
652
+ /**
653
+ * A picked file goes into the box in place of what was typed, with a space after it. A folder goes in with its "/",
654
+ * and its own files show next.
655
+ */
656
+ const chooseFile = (item) => {
657
+ const written = mentionText(item.path);
658
+ const rest = text.slice(mention.end);
659
+ const space = item.dir || /^\s/.test(rest) ? "" : " ";
660
+ const at = mention.start + written.length + (item.dir ? 0 : 1);
661
+
662
+ update(`${text.slice(0, mention.start)}${written}${space}${rest}`, at);
663
+ requestAnimationFrame(() => {
664
+ const element = box.current;
665
+
666
+ if (!element) {
667
+ return;
668
+ }
669
+
670
+ element.focus();
671
+ element.setSelectionRange(at, at);
672
+ });
673
+ };
674
+
675
+ /** A tapped suggestion: commands that take text, and prompt templates, fill the box; the others run at once. */
676
+ const choose = (command) => {
677
+ if (command.args || command.template) {
678
+ update(`/${command.name} `);
679
+ focusEnd();
680
+ } else if (store.state.replyQuote) {
681
+ notify("info", "A quote cannot go with a command. Remove the quote to run it.");
682
+ } else {
683
+ runCommand({ command, arg: "" }, `/${command.name}`);
684
+ }
685
+ };
686
+
687
+ const forget = (list) => {
688
+ for (const file of list) {
689
+ if (file.preview) {
690
+ URL.revokeObjectURL(file.preview);
691
+ }
692
+ }
693
+ };
694
+
695
+ // Something in the box: on a phone while Pi works, Send takes the mic's place (style.css).
696
+ const filled = text.trim() !== "" || files.length > 0;
697
+ const uploading = files.some((file) => file.state === "uploading");
698
+ const canSend =
699
+ !sending &&
700
+ !uploading &&
701
+ (text.trim() !== "" ||
702
+ store.state.replyQuote ||
703
+ files.some((file) => file.state === "done"));
704
+
705
+ /** What went out stays for ↑; its pastes are done with. */
706
+ const sent = (full) => {
707
+ if (full.length <= REMEMBER_CHARS) {
708
+ remember(full, historyScope);
709
+ }
710
+
711
+ setPastes({});
712
+ savePastes(conversationId, {});
713
+ setBrowsing(null);
714
+ update("");
715
+ };
716
+
717
+ /** Run `!command` in the session's folder. Its entry shows once it is done; until then, a row says it runs. */
718
+ const runShell = async (full) => {
719
+ const command = full.replace(/^!!?/, "").trim();
720
+
721
+ if (command === "") {
722
+ return notify("info", "Say which command to run, such as !git status.");
723
+ }
724
+
725
+ setSending(true);
726
+ const started = await attempt(() =>
727
+ actions.shell(command, !full.startsWith("!!"), (requestId.current ??= uid())),
728
+ );
729
+
730
+ setSending(false);
731
+
732
+ if (!started) {
733
+ return;
734
+ }
735
+
736
+ store.set((state) => ({
737
+ pendingShells: [
738
+ ...state.pendingShells,
739
+ { taskId: started.taskId, command, conversationId, at: Date.now() },
740
+ ],
741
+ }));
742
+ requestId.current = null;
743
+ sent(full);
744
+ };
745
+
746
+ const send = async () => {
747
+ if (!canSend) {
748
+ return;
749
+ }
750
+
751
+ // A command runs or expands only when it starts the message: a quote in front would stop that.
752
+ if (
753
+ store.state.replyQuote &&
754
+ (parsed || shell || template || text.trimStart().startsWith("/skill:"))
755
+ ) {
756
+ return notify("info", "A quote cannot go with a command. Remove the quote to run it.");
757
+ }
758
+
759
+ // What shows is what goes: words still coming would land in the emptied box.
760
+ dictation.stop(true);
761
+ const full = expandPastes(text, pastes);
762
+
763
+ if (parsed) {
764
+ if (full.length <= REMEMBER_CHARS) {
765
+ remember(full, historyScope);
766
+ }
767
+
768
+ return runCommand(parseCommand(full) ?? parsed, full);
769
+ }
770
+
771
+ if (shell) {
772
+ return runShell(full);
773
+ }
774
+
775
+ setSending(true);
776
+ const attachments = files
777
+ .filter((file) => file.state === "done")
778
+ .map((file) => file.attachment);
779
+ const ok = await attempt(() =>
780
+ actions.submit(
781
+ withQuote(store.state.replyQuote, full),
782
+ attachments,
783
+ busy ? sendMode : "followUp",
784
+ inlineFiles && mentionsFiles,
785
+ ),
786
+ );
787
+
788
+ setSending(false);
789
+
790
+ if (ok) {
791
+ // Interrupting stops the run: do not let the next message stop one by habit.
792
+ if (sendMode === "interrupt") {
793
+ setSendMode("steer");
794
+ }
795
+
796
+ sent(full);
797
+ store.set({ replyQuote: null });
798
+ forget(files);
799
+ setFiles([]);
800
+
801
+ if (!coarse) {
802
+ box.current?.focus();
803
+ }
804
+ }
805
+ };
806
+
807
+ const editQueued = async (item) => {
808
+ const back = await attempt(() => actions.editQueued(item.id));
809
+
810
+ if (!back) {
811
+ return;
812
+ }
813
+
814
+ const current = drafts.get(conversationId);
815
+ const at = back.text.length;
816
+
817
+ setReading(null);
818
+ update(current.trim() === "" ? back.text : `${back.text}\n${current}`, at);
819
+ setFiles((list) => [
820
+ ...back.attachments.map((attachment) => ({
821
+ key: uid(),
822
+ name: attachment.name,
823
+ size: attachment.size,
824
+ state: "done",
825
+ preview: attachment.mime.startsWith("image/") ? fileUrl(attachment.path) : null,
826
+ attachment,
827
+ })),
828
+ ...list,
829
+ ]);
830
+ requestAnimationFrame(() => {
831
+ box.current?.focus();
832
+ box.current?.setSelectionRange(at, at);
833
+ });
834
+ };
835
+
836
+ /** Put a message sent before into the box, to send again or change. */
837
+ const recall = (value, at = value.length) => {
838
+ update(value, at);
839
+ requestAnimationFrame(() => box.current?.setSelectionRange(at, at));
840
+ };
841
+
842
+ /**
843
+ * ↑ in an empty box, or with the caret at its very start, goes back through what was sent; once going back, ↑ on
844
+ * the first line goes further and ↓ on the last line comes forward, then to the draft. A draft is never replaced by
845
+ * moving the caret up through it.
846
+ */
847
+ const browseHistory = (event) => {
848
+ const element = event.currentTarget;
849
+
850
+ if (element.selectionStart !== element.selectionEnd) {
851
+ return false;
852
+ }
853
+
854
+ const list = sentHistory(historyScope);
855
+
856
+ if (event.key === "ArrowUp") {
857
+ const starts =
858
+ text === "" ||
859
+ element.selectionStart === 0 ||
860
+ (browsing !== null && !text.slice(0, element.selectionStart).includes("\n"));
861
+
862
+ if (!starts) {
863
+ return false;
864
+ }
865
+
866
+ const index = (browsing?.index ?? list.length) - 1;
867
+
868
+ if (index < 0) {
869
+ return false;
870
+ }
871
+
872
+ setBrowsing({ index, draft: browsing?.draft ?? text });
873
+ recall(list[index]);
874
+
875
+ return true;
876
+ }
877
+
878
+ if (browsing === null || text.slice(element.selectionEnd).includes("\n")) {
879
+ return false;
880
+ }
881
+
882
+ const index = browsing.index + 1;
883
+
884
+ if (index < list.length) {
885
+ setBrowsing({ ...browsing, index });
886
+ recall(list[index]);
887
+ } else {
888
+ setBrowsing(null);
889
+ recall(browsing.draft);
890
+ }
891
+
892
+ return true;
893
+ };
894
+
895
+ const onKey = (event) => {
896
+ // A module's key (`pocket.composerKey`) comes first: it may take any key, the box's own too.
897
+ const keyed = keyBox(event.currentTarget, "session", (value, start, end) => {
898
+ update(value, start);
899
+ requestAnimationFrame(() => box.current?.setSelectionRange(start, end));
900
+ });
901
+
902
+ if (boxKey(event, keyed)) {
903
+ event.preventDefault();
904
+
905
+ return;
906
+ }
907
+
908
+ if (
909
+ event.ctrlKey &&
910
+ !event.metaKey &&
911
+ !event.altKey &&
912
+ !event.shiftKey &&
913
+ event.key.toLowerCase() === "r"
914
+ ) {
915
+ event.preventDefault();
916
+ setSearching(!searching);
917
+ setPick(0);
918
+
919
+ return;
920
+ }
921
+
922
+ // While searching, these keys are the search's: with nothing found, Enter must not send the search words.
923
+ if (searching && !event.isComposing) {
924
+ const move = { ArrowDown: 1, ArrowUp: -1 }[event.key];
925
+
926
+ if (move !== undefined) {
927
+ event.preventDefault();
928
+
929
+ if (recalled.length > 0) {
930
+ setPick(
931
+ (Math.min(pick, recalled.length - 1) + move + recalled.length) %
932
+ recalled.length,
933
+ );
934
+ }
935
+
936
+ return;
937
+ }
938
+
939
+ if (event.key === "Escape") {
940
+ event.preventDefault();
941
+ setSearching(false);
942
+
943
+ return;
944
+ }
945
+
946
+ if ((event.key === "Enter" || event.key === "Tab") && !event.shiftKey) {
947
+ event.preventDefault();
948
+
949
+ if (chosenRecall === undefined) {
950
+ return;
951
+ }
952
+
953
+ setSearching(false);
954
+ recall(chosenRecall);
955
+
956
+ return;
957
+ }
958
+ }
959
+
960
+ if (matches.length > 0 && !event.isComposing) {
961
+ const move = { ArrowDown: 1, ArrowUp: -1 }[event.key];
962
+
963
+ if (move !== undefined) {
964
+ event.preventDefault();
965
+ setPick(
966
+ (Math.min(pick, matches.length - 1) + move + matches.length) % matches.length,
967
+ );
968
+
969
+ return;
970
+ }
971
+
972
+ if (event.key === "Escape") {
973
+ event.preventDefault();
974
+ setHiddenMention(mention.start);
975
+
976
+ return;
977
+ }
978
+
979
+ // Tab completes; Enter completes too, unless the file's path is typed out already, which sends.
980
+ const typedOut = !chosenFile.dir && mention.query === chosenFile.path;
981
+
982
+ if (
983
+ event.key === "Tab" ||
984
+ (event.key === "Enter" && !event.shiftKey && !coarse && !typedOut)
985
+ ) {
986
+ event.preventDefault();
987
+ chooseFile(chosenFile);
988
+
989
+ return;
990
+ }
991
+ }
992
+
993
+ if (suggestions.length > 0 && !event.isComposing) {
994
+ const move = { ArrowDown: 1, ArrowUp: -1 }[event.key];
995
+
996
+ if (move !== undefined) {
997
+ event.preventDefault();
998
+ setPick(
999
+ (Math.min(pick, suggestions.length - 1) + move + suggestions.length) %
1000
+ suggestions.length,
1001
+ );
1002
+
1003
+ return;
1004
+ }
1005
+
1006
+ if (event.key === "Escape") {
1007
+ event.preventDefault();
1008
+ setHideCommands(true);
1009
+
1010
+ return;
1011
+ }
1012
+
1013
+ // Tab completes; Enter completes too, unless the name is typed out already, which runs it.
1014
+ const typedOut = parsed && text.trim() === `/${chosen.name}`;
1015
+
1016
+ if (
1017
+ event.key === "Tab" ||
1018
+ (event.key === "Enter" && !event.shiftKey && !coarse && !typedOut)
1019
+ ) {
1020
+ event.preventDefault();
1021
+ choose(chosen);
1022
+
1023
+ return;
1024
+ }
1025
+ }
1026
+
1027
+ if (
1028
+ (event.key === "ArrowUp" || event.key === "ArrowDown") &&
1029
+ !event.isComposing &&
1030
+ !event.shiftKey &&
1031
+ !event.altKey &&
1032
+ !event.ctrlKey &&
1033
+ !event.metaKey
1034
+ ) {
1035
+ if (browseHistory(event)) {
1036
+ event.preventDefault();
1037
+ }
1038
+
1039
+ return;
1040
+ }
1041
+
1042
+ if (event.key === "Enter" && !event.shiftKey && !coarse && !event.isComposing) {
1043
+ event.preventDefault();
1044
+ send();
1045
+ }
1046
+ };
1047
+
1048
+ const addFiles = (list) => {
1049
+ for (const file of list) {
1050
+ const key = uid();
1051
+ const preview = file.type.startsWith("image/") ? URL.createObjectURL(file) : null;
1052
+
1053
+ setFiles((current) => [
1054
+ ...current,
1055
+ { key, name: file.name, size: file.size, state: "uploading", preview },
1056
+ ]);
1057
+ actions.upload(file).then(
1058
+ (attachment) =>
1059
+ setFiles((current) =>
1060
+ current.map((each) =>
1061
+ each.key === key ? { ...each, state: "done", attachment } : each,
1062
+ ),
1063
+ ),
1064
+ (error) => {
1065
+ notify("error", `Upload failed: ${error.message}`);
1066
+
1067
+ if (preview) {
1068
+ URL.revokeObjectURL(preview);
1069
+ }
1070
+
1071
+ setFiles((current) => current.filter((each) => each.key !== key));
1072
+ },
1073
+ );
1074
+ }
1075
+ };
1076
+
1077
+ const onPaste = (event) => {
1078
+ const pastedFiles = [...(event.clipboardData?.files ?? [])];
1079
+
1080
+ if (pastedFiles.length > 0) {
1081
+ event.preventDefault();
1082
+ addFiles(pastedFiles);
1083
+
1084
+ return;
1085
+ }
1086
+
1087
+ // A long paste goes in as a placeholder, so the box stays readable; the message goes out with the text.
1088
+ const value = event.clipboardData?.getData("text/plain") ?? "";
1089
+ const lines = value.replace(/\n$/, "").split("\n").length;
1090
+
1091
+ if (lines <= PASTE_LINES && value.length <= PASTE_CHARS) {
1092
+ return;
1093
+ }
1094
+
1095
+ event.preventDefault();
1096
+ const n = Math.max(0, ...Object.keys(pastes).map(Number)) + 1;
1097
+ const label = `[Pasted text #${n} · ${lines > 1 ? `${lines} lines` : `${value.length} characters`}]`;
1098
+ const next = { ...pastes, [n]: value };
1099
+
1100
+ setPastes(next);
1101
+ savePastes(conversationId, next);
1102
+ const element = event.currentTarget;
1103
+ const at = element.selectionStart + label.length;
1104
+
1105
+ recall(
1106
+ `${text.slice(0, element.selectionStart)}${label}${text.slice(element.selectionEnd)}`,
1107
+ at,
1108
+ );
1109
+ };
1110
+
1111
+ const placeholder = dictation.listening
1112
+ ? "Listening…"
1113
+ : busy
1114
+ ? sendMode === "steer"
1115
+ ? "Steer the current run…"
1116
+ : sendMode === "interrupt"
1117
+ ? "Stop the run and send this now…"
1118
+ : "Queue a message for after this run…"
1119
+ : "Ask Pi anything…";
1120
+ const inbox = view.inbox ?? [];
1121
+ const { me, users } = store.state;
1122
+ const queuedBy = (item) =>
1123
+ item.by === undefined
1124
+ ? ""
1125
+ : item.by === me?.id
1126
+ ? " · you"
1127
+ : ` · ${users.find((user) => user.id === item.by)?.name ?? "someone"}`;
1128
+
1129
+ useDock(dock);
1130
+ // View only now, or someone else took the wheel: the box goes, and dictation with it.
1131
+ const writes = !collab() || (canSteer() && !(view.turns?.on && view.turns.driver !== me?.id));
1132
+
1133
+ useEffect(() => {
1134
+ if (!writes) {
1135
+ dictation.stop(true);
1136
+ }
1137
+ }, [writes]);
1138
+
1139
+ if (collab() && !canSteer()) {
1140
+ return html`<footer class="composer-wrap" data-part="composer">
1141
+ <div class="dock" data-part="dock" ref=${dock}>
1142
+ <${TypingLine} where="pi" />
1143
+ <${SubagentsBar} />
1144
+ </div>
1145
+ <${ParentSessionButton} />
1146
+ <div class="view-only">
1147
+ <span>
1148
+ <strong>View only.</strong> You can read along, react, and chat with the people here.
1149
+ </span>
1150
+ <button class="button small" onClick=${() => openSheet({ type: "chat" })}>
1151
+ <${Icon} name="chat" size=${15} /> Chat
1152
+ </button>
1153
+ </div>
1154
+ <${StatusLine} />
1155
+ </footer>`;
1156
+ }
1157
+
1158
+ const turns = view.turns;
1159
+ const blocked = collab() && turns?.on && turns.driver !== me?.id;
1160
+ const level =
1161
+ agent?.thinkingLevel && agent.thinkingLevel !== "off" && agent.reasoning
1162
+ ? agent.thinkingLevel
1163
+ : null;
1164
+
1165
+ return html`<footer class="composer-wrap" data-part="composer">
1166
+ <div class="dock" data-part="dock" ref=${dock}>
1167
+ <${TypingLine} where="pi" />
1168
+ ${
1169
+ // How many wait: shown when the queue does not show them all (`dock.js`).
1170
+ inbox.length > 0 &&
1171
+ html`<div class="inbox-count">
1172
+ ${inbox.length} ${inbox.length === 1 ? "message" : "messages"} waiting for Pi
1173
+ </div>`
1174
+ }
1175
+ ${
1176
+ inbox.length > 0 &&
1177
+ html`<div class="inbox">
1178
+ ${inbox.map(
1179
+ (item) => html`<div class="queued">
1180
+ <span class="queued-mode">
1181
+ ${queuedMode(item)}
1182
+ <span class="muted">${queuedBy(item)}</span>
1183
+ </span>
1184
+ <button
1185
+ class=${`queued-text ${reading === item.id ? "open" : ""}`}
1186
+ aria-expanded=${reading === item.id}
1187
+ onClick=${() => setReading(reading === item.id ? null : item.id)}
1188
+ >
1189
+ ${queuedText(item)}
1190
+ </button>
1191
+ ${
1192
+ canSteer() &&
1193
+ (!blocked || item.by === me?.id) &&
1194
+ html`<button
1195
+ class="icon-button small queued-remove"
1196
+ aria-label=${queuedReports(item) ? "Discard these reports" : "Withdraw"}
1197
+ title=${queuedReports(item) ? "Discard these reports: Pi will not get them" : "Withdraw"}
1198
+ onClick=${() => attempt(() => actions.withdraw(item.id))}
1199
+ >
1200
+ <${Icon} name="close" size=${13} />
1201
+ </button>`
1202
+ }
1203
+ ${
1204
+ // Tapped open, one's own message: move it, or send it now. Only its sender can.
1205
+ reading === item.id &&
1206
+ item.by !== undefined &&
1207
+ item.by === me?.id &&
1208
+ canSteer() &&
1209
+ !blocked &&
1210
+ (item.mode === "steer" || item.mode === "followUp") &&
1211
+ html`<div class="queued-actions">
1212
+ <button
1213
+ class="button small"
1214
+ title="Take it back into the message box to change it"
1215
+ onClick=${() => editQueued(item)}
1216
+ >
1217
+ Edit
1218
+ </button>
1219
+ <button
1220
+ class="button small"
1221
+ title=${modeHint(item.mode === "steer" ? "followUp" : "steer")}
1222
+ onClick=${() =>
1223
+ attempt(() =>
1224
+ actions.move(
1225
+ item.id,
1226
+ item.mode === "steer" ? "followUp" : "steer",
1227
+ ),
1228
+ )}
1229
+ >
1230
+ ${item.mode === "steer" ? "Move to queue" : "Steer now"}
1231
+ </button>
1232
+ <button
1233
+ class=${`button small ${interrupting === item.id ? "danger" : ""}`}
1234
+ title=${
1235
+ interrupting === item.id
1236
+ ? "Tap again to stop the run and send this now. The other queued messages stay queued"
1237
+ : QUEUED_INTERRUPT_HINT
1238
+ }
1239
+ onClick=${() => {
1240
+ if (CONFIRM_INTERRUPT && interrupting !== item.id) {
1241
+ setInterrupting(item.id);
1242
+
1243
+ return;
1244
+ }
1245
+
1246
+ // A third quick tap must not send it again.
1247
+ setInterrupting(null);
1248
+ void attempt(() => actions.move(item.id, "interrupt"));
1249
+ }}
1250
+ >
1251
+ ${interrupting === item.id ? "Interrupt?" : "Interrupt"}
1252
+ </button>
1253
+ </div>`
1254
+ }
1255
+ </div>`,
1256
+ )}
1257
+ </div>`
1258
+ }
1259
+ ${collab() && html`<${DriverBar} />`}
1260
+ <${PlanBar} blocked=${blocked} />
1261
+ <${GoalBar} />
1262
+ <${WatchBar} />
1263
+ <${SubagentsBar} />
1264
+ <${TrustBar} />
1265
+ </div>
1266
+ <${ParentSessionButton} />
1267
+ ${
1268
+ blocked
1269
+ ? html`${
1270
+ busy &&
1271
+ html`<div class="composer-row stop-only">
1272
+ <span class="muted small grow">Pi is working…</span>
1273
+ <${StopButton} />
1274
+ </div>`
1275
+ }`
1276
+ : html`${
1277
+ searching &&
1278
+ html`<div
1279
+ class="commands history-options"
1280
+ role="listbox"
1281
+ aria-label="Sent before"
1282
+ ref=${list}
1283
+ >
1284
+ <div class="file-note">
1285
+ Sent in this session${text.trim() ? ` with “${text.trim()}”` : ""} · Enter puts it in the box · Esc closes
1286
+ </div>
1287
+ ${recalled.map(
1288
+ (each) => html`<button
1289
+ class=${`command ${each === chosenRecall ? "on" : ""}`}
1290
+ role="option"
1291
+ aria-selected=${each === chosenRecall}
1292
+ onMouseDown=${(event) => event.preventDefault()}
1293
+ onClick=${() => {
1294
+ setSearching(false);
1295
+ recall(each);
1296
+ }}
1297
+ >
1298
+ <span class="command-description history-text">
1299
+ ${each.replace(/\s+/g, " ")}
1300
+ </span>
1301
+ </button>`,
1302
+ )}
1303
+ ${
1304
+ recalled.length === 0 &&
1305
+ html`<div class="file-note">
1306
+ Nothing you sent from this browser in this session matches.
1307
+ </div>`
1308
+ }
1309
+ </div>`
1310
+ }
1311
+ ${
1312
+ shell &&
1313
+ html`<div class="command-hint">
1314
+ <span class="command-name">${shell.context ? "!" : "!!"}</span> <span class="muted">· runs in this session's folder · ${shell.context ? "Pi sees the output (!! to keep it from Pi)" : "only the people here see the output"}</span>
1315
+ </div>`
1316
+ }
1317
+ ${
1318
+ pasted &&
1319
+ !shell &&
1320
+ html`<div class="command-hint muted">
1321
+ Pasted text goes out in full where its placeholder is.
1322
+ </div>`
1323
+ }
1324
+ ${
1325
+ mentionsFiles &&
1326
+ !mention &&
1327
+ !searching &&
1328
+ html`<div class="command-hint wraps">
1329
+ <span class="muted">
1330
+ ${inlineFiles ? "Mentioned files go with the message." : "Pi reads the files you mention."}
1331
+ </span>
1332
+ ${" "}
1333
+ <button
1334
+ class="link small"
1335
+ onMouseDown=${(event) => event.preventDefault()}
1336
+ onClick=${() => {
1337
+ localStorage.setItem(INLINE_KEY, inlineFiles ? "0" : "1");
1338
+ setInlineFiles(!inlineFiles);
1339
+ }}
1340
+ >
1341
+ ${inlineFiles ? "Let Pi read them" : "Send them along"}
1342
+ </button>
1343
+ </div>`
1344
+ }
1345
+ ${
1346
+ mention &&
1347
+ (matches.length > 0 || found.loading) &&
1348
+ html`<div
1349
+ class="commands file-options"
1350
+ role="listbox"
1351
+ aria-label="Files"
1352
+ ref=${list}
1353
+ >
1354
+ ${matches.map(
1355
+ (item) => html`<button
1356
+ key=${item.path}
1357
+ class=${`command file-option ${item === chosenFile ? "on" : ""}`}
1358
+ role="option"
1359
+ aria-selected=${item === chosenFile}
1360
+ onMouseDown=${(event) => event.preventDefault()}
1361
+ onClick=${() => chooseFile(item)}
1362
+ >
1363
+ <${Icon}
1364
+ name=${item.dir ? "folder" : "file"}
1365
+ size=${14}
1366
+ class="file-icon"
1367
+ />
1368
+ <span class="file-name">
1369
+ <${Marked} text=${item.name} hits=${item.nameHits} />
1370
+ ${item.dir ? "/" : ""}
1371
+ </span>
1372
+ <span class="command-description">
1373
+ <${Marked} text=${item.parent} hits=${item.parentHits} />
1374
+ </span>
1375
+ </button>`,
1376
+ )}
1377
+ ${matches.length === 0 && html`<div class="file-note">Finding files…</div>`}
1378
+ ${
1379
+ found.truncated &&
1380
+ html`<div class="file-note">
1381
+ A large folder: only the files nearest its top are listed.
1382
+ </div>`
1383
+ }
1384
+ </div>`
1385
+ }
1386
+ ${
1387
+ suggestions.length > 0 &&
1388
+ html`<div class="commands" role="listbox" ref=${list}>
1389
+ ${suggestions.map(
1390
+ (command) => html`<button
1391
+ class=${`command ${command === chosen ? "on" : ""}`}
1392
+ role="option"
1393
+ aria-selected=${command === chosen}
1394
+ onMouseDown=${(event) => event.preventDefault()}
1395
+ onClick=${() => choose(command)}
1396
+ >
1397
+ <span class="command-name">/${command.name}</span>
1398
+ ${
1399
+ command.args &&
1400
+ html`<span class="command-args">${command.args}</span>`
1401
+ }
1402
+ <span class="command-description">${command.description}</span>
1403
+ </button>`,
1404
+ )}
1405
+ </div>`
1406
+ }
1407
+ ${
1408
+ suggestions.length === 0 &&
1409
+ parsed &&
1410
+ html`<div class="command-hint">
1411
+ <span class="command-name">/${parsed.command.name}</span>
1412
+ ${
1413
+ parsed.command.args &&
1414
+ html` <span class="command-args">${parsed.command.args}</span>`
1415
+ } <span class="muted">· ${parsed.command.description} · not sent to Pi</span>
1416
+ </div>`
1417
+ }
1418
+ ${
1419
+ suggestions.length === 0 &&
1420
+ template &&
1421
+ html`<div class="command-hint">
1422
+ <span class="command-name">/${template.name}</span>
1423
+ ${
1424
+ template.args &&
1425
+ html` <span class="command-args">${template.args}</span>`
1426
+ } <span class="muted">· ${template.skill ? "skill · Pi gets its instructions with your request" : "prompt template · Pi gets it filled in"}</span>
1427
+ </div>`
1428
+ }
1429
+ <div
1430
+ class=${`composer ${busy ? "busy" : ""} ${filled ? "filled" : ""}`}
1431
+ data-part="message-box"
1432
+ onClick=${(event) => {
1433
+ // The box is one target: a tap on its edge, around the files sent along, between its buttons,
1434
+ // or on Send with nothing to send (a disabled button takes no taps), goes to the text.
1435
+ if (
1436
+ event.target === event.currentTarget ||
1437
+ event.target.classList.contains("composer-row") ||
1438
+ event.target.classList.contains("files")
1439
+ ) {
1440
+ box.current?.focus();
1441
+ }
1442
+ }}
1443
+ onDragOver=${(event) => event.preventDefault()}
1444
+ onDrop=${(event) => {
1445
+ event.preventDefault();
1446
+ addFiles([...(event.dataTransfer?.files ?? [])]);
1447
+ }}
1448
+ >
1449
+ ${
1450
+ files.length > 0 &&
1451
+ html`<div class="files">
1452
+ ${files.map(
1453
+ (
1454
+ file,
1455
+ ) => html`<span class=${`chip ${file.preview ? "with-thumb" : ""}`}>
1456
+ ${
1457
+ file.preview &&
1458
+ html`<img class="chip-thumb" src=${file.preview} alt="" />`
1459
+ }
1460
+ ${file.state === "uploading" ? html`<${Spinner} />` : file.preview ? "" : html`<${Icon} name="clip" size=${13} />`}
1461
+ <span class="chip-name" title=${file.name}>${file.name}</span>
1462
+ <span class="muted">${formatBytes(file.size)}</span>
1463
+ <button
1464
+ class="icon-button small"
1465
+ aria-label=${`Remove ${file.name}`}
1466
+ onClick=${() => {
1467
+ forget([file]);
1468
+ setFiles((current) =>
1469
+ current.filter((each) => each.key !== file.key),
1470
+ );
1471
+ }}
1472
+ >
1473
+ <${Icon} name="close" size=${12} />
1474
+ </button>
1475
+ </span>`,
1476
+ )}
1477
+ </div>`
1478
+ }
1479
+ ${
1480
+ store.state.replyQuote &&
1481
+ html`<div class="quote-strip" data-part="quote-strip">
1482
+ <${Icon} name="reply" size=${13} />
1483
+ <span class="quote-strip-text">${store.state.replyQuote}</span>
1484
+ <button
1485
+ class="icon-button small"
1486
+ aria-label="Remove the quote"
1487
+ onClick=${() => store.set({ replyQuote: null })}
1488
+ >
1489
+ <${Icon} name="close" size=${12} />
1490
+ </button>
1491
+ </div>`
1492
+ }
1493
+ <textarea
1494
+ ref=${setBox}
1495
+ rows="1"
1496
+ value=${text}
1497
+ placeholder=${placeholder}
1498
+ onInput=${(event) => {
1499
+ setBrowsing(null);
1500
+ update(event.currentTarget.value, event.currentTarget.selectionStart);
1501
+ }}
1502
+ onKeyDown=${onKey}
1503
+ onKeyUp=${(event) => setCaret(event.currentTarget.selectionStart)}
1504
+ onClick=${(event) => setCaret(event.currentTarget.selectionStart)}
1505
+ onFocus=${() => loadFiles({ ifMissing: true })}
1506
+ onPaste=${onPaste}
1507
+ enterkeyhint=${coarse ? "enter" : "send"}
1508
+ ></textarea>
1509
+ <div class="composer-row" data-part="composer-tools">
1510
+ ${slotItems("composer", { picker, agent, level, view }).map(({ node }) => node)}
1511
+ <input
1512
+ ref=${picker}
1513
+ type="file"
1514
+ multiple
1515
+ hidden
1516
+ onChange=${(event) => {
1517
+ addFiles([...event.currentTarget.files]);
1518
+ event.currentTarget.value = "";
1519
+ }}
1520
+ />
1521
+ <span class="grow"></span>
1522
+ ${
1523
+ busy &&
1524
+ html`<div
1525
+ class="mode-switch"
1526
+ data-part="composer-button mode-switch"
1527
+ role="radiogroup"
1528
+ aria-label="Send as"
1529
+ onKeyDown=${(event) => {
1530
+ // Arrows move between them, as in any group of radio buttons.
1531
+ if (/^Arrow(Left|Right|Up|Down)$/.test(event.key)) {
1532
+ const group = event.currentTarget;
1533
+ const modes = SEND_MODES.map(([value]) => value);
1534
+ const step = /^Arrow(Left|Up)$/.test(event.key) ? -1 : 1;
1535
+
1536
+ event.preventDefault();
1537
+ setSendMode(
1538
+ modes[
1539
+ (modes.indexOf(sendMode) + step + modes.length) %
1540
+ modes.length
1541
+ ],
1542
+ );
1543
+ requestAnimationFrame(() =>
1544
+ group.querySelector('[aria-checked="true"]')?.focus(),
1545
+ );
1546
+ }
1547
+ }}
1548
+ >
1549
+ ${SEND_MODES.map(
1550
+ ([value, label, tip]) => html`<button
1551
+ role="radio"
1552
+ aria-checked=${sendMode === value ? "true" : "false"}
1553
+ tabindex=${sendMode === value ? "0" : "-1"}
1554
+ class=${`${sendMode === value ? "on" : ""} ${value === "interrupt" ? "interrupt" : ""}`}
1555
+ title=${tip}
1556
+ onMouseDown=${(event) => event.preventDefault()}
1557
+ onClick=${() => setSendMode(value)}
1558
+ >
1559
+ ${label}
1560
+ </button>`,
1561
+ )}
1562
+ </div>`
1563
+ }
1564
+ <${MicButton}
1565
+ dictation=${dictation}
1566
+ class="composer-mic"
1567
+ part="composer-button"
1568
+ />
1569
+ <button
1570
+ class=${`send-button ${canSend ? "ready" : ""}`}
1571
+ data-part="send-button"
1572
+ data-state=${canSend ? "ready" : undefined}
1573
+ aria-label="Send"
1574
+ title=${coarse ? "Send" : "Send (Enter)"}
1575
+ disabled=${!canSend}
1576
+ onClick=${send}
1577
+ >
1578
+ ${
1579
+ sending
1580
+ ? html`<${Spinner} />`
1581
+ : html`<${Icon} name="send" size=${16} stroke=${2.4} />`
1582
+ }
1583
+ </button>
1584
+ ${busy && html`<${StopButton} />`}
1585
+ </div>
1586
+ </div>`
1587
+ }
1588
+ <${StatusLine} />
1589
+ </footer>`;
1590
+ }
1591
+
1592
+ // The buttons on the left of the message box's row: the app's own items of the `composer` slot (slots.js), which a
1593
+ // person can hide and reorder in Appearance, with extensions' after them. Each gets what the box knows: its file
1594
+ // picker, the model and thinking level, and the session's view. Send, Stop, the mic, and Steer and Queue stay on the
1595
+ // right, always.
1596
+ defineItem("composer", {
1597
+ id: "core:places",
1598
+ label: "Places (phones)",
1599
+ order: 100,
1600
+ render: () => html`<${PlacesButton} />`,
1601
+ });
1602
+ defineItem("composer", {
1603
+ id: "core:attach",
1604
+ label: "Attach files",
1605
+ order: 200,
1606
+ render: ({ picker }) =>
1607
+ html`<button
1608
+ class="icon-button attach-button"
1609
+ data-part="composer-button"
1610
+ aria-label="Attach files"
1611
+ title="Attach files"
1612
+ onClick=${() => picker.current?.click()}
1613
+ >
1614
+ <${Icon} name="clip" size=${17} />
1615
+ </button>`,
1616
+ });
1617
+ defineItem("composer", {
1618
+ id: "core:model",
1619
+ label: "Model",
1620
+ order: 300,
1621
+ render: ({ agent, level }) =>
1622
+ html`<button
1623
+ class=${`model-chip ${agent?.available === false ? "warn" : ""}`}
1624
+ data-part="model-chip"
1625
+ aria-label=${`Model: ${modelLabel(agent)}${level ? `, thinking ${level}` : ""}`}
1626
+ title=${`Model and thinking: ${modelLabel(agent)}${level ? `, ${level}` : ""}`}
1627
+ onClick=${() => openSheet({ type: "model" })}
1628
+ >
1629
+ <${Icon} name="sparkle" size=${12} class="model-spark" />
1630
+ <span class="model-name">${shortModel(agent)}</span>
1631
+ ${level && html`<span class="model-level">${level}</span>`}
1632
+ <${Icon} name="chevron" size=${12} stroke=${2.2} class="model-caret" />
1633
+ </button>`,
1634
+ });
1635
+ defineItem("composer", {
1636
+ id: "core:plan",
1637
+ label: "Plan",
1638
+ order: 400,
1639
+ render: ({ view }) =>
1640
+ planAvailable() &&
1641
+ view.conversation?.kind !== "subagent" &&
1642
+ html`<button
1643
+ class=${`plan-chip ${view.plan?.on ? "on" : ""}`}
1644
+ data-part="composer-button plan-chip"
1645
+ aria-pressed=${view.plan?.on === true}
1646
+ title="Plan mode: Pi reads and proposes, and changes nothing until you approve"
1647
+ onMouseDown=${(event) => event.preventDefault()}
1648
+ onClick=${() => attempt(() => actions.setPlan(!view.plan?.on))}
1649
+ >
1650
+ Plan
1651
+ </button>`,
1652
+ });
1653
+
1654
+ /** The browser sizes the message box to its text itself (`field-sizing` in style.css): nothing to measure. */
1655
+ const SIZES_ITSELF = globalThis.CSS?.supports?.("field-sizing", "content") ?? false;
1656
+
1657
+ /**
1658
+ * The message box grows with what is written, to 40% of the screen; its least height (two lines, or one on a short
1659
+ * screen) is the stylesheet's, and changes with the screen. Browsers without `field-sizing` measure it here.
1660
+ */
1661
+ function fitBox(element) {
1662
+ if (!element || SIZES_ITSELF || !element.isConnected) {
1663
+ return;
1664
+ }
1665
+
1666
+ element.style.height = "auto";
1667
+ element.style.height = `${Math.min(element.scrollHeight, innerHeight * 0.4)}px`;
1668
+ }
1669
+
1670
+ /** A model's short name for the message box: "opus 4.5" for "Claude Opus 4.5". */
1671
+ export const shortModel = (agent) =>
1672
+ modelLabel(agent)
1673
+ // A provider's own prefix ("Anthropic: Claude Opus 4.5"), then the family's name.
1674
+ .replace(/^[^:]{1,24}:\s*/, "")
1675
+ .replace(/^(?:anthropic\s+)?claude\s+/i, "")
1676
+ .toLowerCase();
1677
+
1678
+ /** Stop the run: a square in the failure color. */
1679
+ function StopButton() {
1680
+ return html`<button
1681
+ class="stop-button"
1682
+ data-part="composer-button stop-button"
1683
+ aria-label="Stop"
1684
+ title="Stop (Esc twice)"
1685
+ onClick=${() => attempt(actions.abort)}
1686
+ >
1687
+ <span class="stop-square" aria-hidden="true"></span>
1688
+ </button>`;
1689
+ }
1690
+
1691
+ /**
1692
+ * Phones: the session's places (Files, Changes, the browser…) from beside the message box, where a thumb reaches; the
1693
+ * top bar's buttons are a stretch with one hand. A dot when the chat has news or a page is open.
1694
+ */
1695
+ function PlacesButton() {
1696
+ const { browser } = store.state;
1697
+ const news =
1698
+ (collab() && chatUnread() > 0) ||
1699
+ (browser?.open && browser.url !== "" && browser.url !== "about:blank");
1700
+
1701
+ return html`<button
1702
+ class="icon-button places-button badge-host"
1703
+ data-part="composer-button"
1704
+ aria-label="Places: Files, Changes, Browser, and more"
1705
+ title="Places (or swipe up here)"
1706
+ onClick=${() => openSheet({ type: "places" })}
1707
+ >
1708
+ <${Icon} name="grid" />
1709
+ ${news && html`<span class="browser-dot" aria-hidden="true"></span>`}
1710
+ </button>`;
1711
+ }
1712
+
1713
+ /**
1714
+ * The status line's shorter forms, in the order a narrow line takes them until it fits on one row: shorter words and
1715
+ * gaps, no "1 here" while you are alone, extensions' items' short forms, the guard's and the context's labels, then the
1716
+ * cache, then the wait for the first token.
1717
+ */
1718
+ const SHORTER = ["words", "here", "ext", "guard", "context", "cache", "wait"];
1719
+ /** What each status line was last fitted for: its text. Its width is the observer's to watch. */
1720
+ const fitted = new WeakMap();
1721
+
1722
+ /** Whether the items that show sit on one row: their middles line up. */
1723
+ function oneRow(line) {
1724
+ const middles = [...line.children]
1725
+ .map((child) => child.getBoundingClientRect())
1726
+ .filter((box) => box.width > 0)
1727
+ .map((box) => box.top + box.height / 2);
1728
+
1729
+ return middles.every((middle) => Math.abs(middle - middles[0]) < 2);
1730
+ }
1731
+
1732
+ /**
1733
+ * The whole line where it fits on one row; otherwise each shorter form in turn, until one does. Only when its text
1734
+ * changed, or `again`: a render that changed nothing measures nothing.
1735
+ */
1736
+ function fitStatus(line, again = false) {
1737
+ if (!line) {
1738
+ return;
1739
+ }
1740
+
1741
+ const key = line.textContent;
1742
+
1743
+ // Hidden, it has no width to fit: the observer hears it show.
1744
+ if ((!again && fitted.get(line) === key) || line.clientWidth === 0) {
1745
+ return;
1746
+ }
1747
+
1748
+ fitted.set(line, key);
1749
+
1750
+ for (let step = 0; step <= SHORTER.length; step++) {
1751
+ line.dataset.short = SHORTER.slice(0, step).join(" ");
1752
+
1753
+ if (oneRow(line)) {
1754
+ return;
1755
+ }
1756
+ }
1757
+ }
1758
+
1759
+ /** Keep the status line in `ref` on one row: after every render, when its width changes, and once the font loads. */
1760
+ function useStatusFit(ref) {
1761
+ useLayoutEffect(() => fitStatus(ref.current));
1762
+ useEffect(() => {
1763
+ const line = ref.current;
1764
+
1765
+ if (!line) {
1766
+ return;
1767
+ }
1768
+
1769
+ let frame = 0;
1770
+ let gone = false;
1771
+ let width = -1;
1772
+ // A new width only (fitting changes the line's height, which this hears too), fitted a frame later.
1773
+ const observer = new ResizeObserver(([entry]) => {
1774
+ if (entry.contentRect.width === width) {
1775
+ return;
1776
+ }
1777
+
1778
+ width = entry.contentRect.width;
1779
+ cancelAnimationFrame(frame);
1780
+ frame = requestAnimationFrame(() => fitStatus(line, true));
1781
+ });
1782
+
1783
+ // Fitted again once a font loads, and when a theme (with fonts of its own) has: its text measures another width.
1784
+ const again = () => !gone && fitStatus(line, true);
1785
+
1786
+ observer.observe(line);
1787
+ document.fonts?.ready.then(again);
1788
+ document.fonts?.addEventListener("loadingdone", again);
1789
+ document.addEventListener("pocket:theme", again);
1790
+
1791
+ return () => {
1792
+ gone = true;
1793
+ cancelAnimationFrame(frame);
1794
+ observer.disconnect();
1795
+ document.fonts?.removeEventListener("loadingdone", again);
1796
+ document.removeEventListener("pocket:theme", again);
1797
+ };
1798
+ }, []);
1799
+ }
1800
+
1801
+ /** Seconds, as the status line says them: 0.4s, 3.2s, 14s. */
1802
+ const seconds = (ms) => (ms >= 10_000 ? `${Math.round(ms / 1000)}s` : `${(ms / 1000).toFixed(1)}s`);
1803
+
1804
+ /**
1805
+ * How fast the newest answer came, once Appearance turns it on: its tokens a second, and how long its first token
1806
+ * took. Narrow, "42 tok/s · 1.2s"; an answer that came in one flush has no speed, only its wait.
1807
+ */
1808
+ function SpeedPart({ stats }) {
1809
+ const rate = stats.tokensPerSec;
1810
+ const wait = stats.ttftMs;
1811
+
1812
+ if (rate === undefined && wait === undefined) {
1813
+ return null;
1814
+ }
1815
+
1816
+ const title = [
1817
+ rate !== undefined && `${rate.toFixed(1)} tokens a second`,
1818
+ wait !== undefined && `its first token after ${(wait / 1000).toFixed(2)}s`,
1819
+ ]
1820
+ .filter(Boolean)
1821
+ .join(", ");
1822
+
1823
+ return html`<span
1824
+ class=${`speed ${rate === undefined ? "wait-only" : ""}`}
1825
+ title=${`How fast the last answer came: ${title}`}
1826
+ >
1827
+ ${
1828
+ rate !== undefined &&
1829
+ html`<span class="rate">
1830
+ <span class="num">${rate < 9.95 ? rate.toFixed(1) : Math.round(rate)}</span>${" "}
1831
+ <span class="long">tokens/s</span>
1832
+ <span class="short">tok/s</span>
1833
+ </span>`
1834
+ }
1835
+ ${
1836
+ wait !== undefined &&
1837
+ html`<span class="wait">
1838
+ <span class="word">first token${" "}</span>
1839
+ <span class="num">${seconds(wait)}</span>
1840
+ </span>`
1841
+ }
1842
+ </span>`;
1843
+ }
1844
+
1845
+ // The status line's items: the app's own items of the `status` slot (slots.js), which a person can hide and reorder in
1846
+ // Appearance, with extensions' before the spend. The connection's warning leads and Lancet Guard ends it, always.
1847
+ defineItem("status", {
1848
+ id: "core:connection",
1849
+ label: "Connection",
1850
+ order: 0,
1851
+ fixed: true,
1852
+ render() {
1853
+ const { connection } = store.state;
1854
+
1855
+ return (
1856
+ connection !== "open" &&
1857
+ html`<span class="warn">
1858
+ ${connection === "connecting" ? "connecting…" : "reconnecting…"}
1859
+ </span>`
1860
+ );
1861
+ },
1862
+ });
1863
+ defineItem("status", {
1864
+ id: "core:here",
1865
+ label: "People here",
1866
+ order: 100,
1867
+ render() {
1868
+ const { view, presence } = store.state;
1869
+ // People, not tabs: one person with a phone and a laptop open is one here (presence has a row per person).
1870
+ const here = presence.length || view.viewers?.length || 1;
1871
+
1872
+ return html`<span
1873
+ class=${`here ${here === 1 ? "alone" : ""}`}
1874
+ title=${`${(view.viewers ?? []).join(", ")}${view.clients > here ? ` · ${view.clients} tabs` : ""}`}
1875
+ >
1876
+ ${here} here
1877
+ </span>`;
1878
+ },
1879
+ });
1880
+ defineItem("status", {
1881
+ id: "core:speed",
1882
+ label: "Reply speed",
1883
+ order: 200,
1884
+ render: () =>
1885
+ prefs().speed === true && html`<${SpeedPart} stats=${store.state.view.stats ?? {}} />`,
1886
+ });
1887
+
1888
+ /** How full the context is: `{ used, window, percent, about }`, or null with no context window known. */
1889
+ function contextFill() {
1890
+ const { view } = store.state;
1891
+ const window = view.agent?.contextWindow;
1892
+
1893
+ if (!window) {
1894
+ return null;
1895
+ }
1896
+
1897
+ const used = view.stats?.contextTokens ?? 0;
1898
+
1899
+ return {
1900
+ used,
1901
+ window,
1902
+ percent: Math.min(100, Math.round((used / window) * 100)),
1903
+ // Compacted since the last answer: what is left, estimated until the next answer measures it.
1904
+ about: view.stats?.contextEstimated ? "~" : "",
1905
+ };
1906
+ }
1907
+
1908
+ const contextTitle = ({ used, window, about }) =>
1909
+ `${about}${formatTokens(used)} of ${formatTokens(window)} tokens in context`;
1910
+
1911
+ defineItem("status", {
1912
+ id: "core:context",
1913
+ label: "Context",
1914
+ order: 300,
1915
+ render() {
1916
+ const fill = contextFill();
1917
+
1918
+ return (
1919
+ fill &&
1920
+ html`<span class="context" title=${contextTitle(fill)}>
1921
+ <span class="word">context</span>
1922
+ <span class=${`meter ${contextLevel(fill.percent)}`} aria-hidden="true">
1923
+ <span style=${`width:${fill.percent}%`}></span>
1924
+ </span>
1925
+ <span class="num">${fill.about}${fill.percent}%</span>
1926
+ </span>`
1927
+ );
1928
+ },
1929
+ detail() {
1930
+ const fill = contextFill();
1931
+
1932
+ return fill && contextTitle(fill);
1933
+ },
1934
+ });
1935
+
1936
+ const cacheRate = () => store.state.view.stats?.cacheRate;
1937
+
1938
+ defineItem("status", {
1939
+ id: "core:cache",
1940
+ label: "Cache",
1941
+ order: 400,
1942
+ render: () =>
1943
+ cacheRate() !== undefined &&
1944
+ html`<span class="cache">
1945
+ cache <span class="num">${Math.round(cacheRate() * 100)}%</span>
1946
+ </span>`,
1947
+ detail: () =>
1948
+ cacheRate() !== undefined &&
1949
+ `${Math.round(cacheRate() * 100)}% of the input came from the cache`,
1950
+ });
1951
+
1952
+ /**
1953
+ * The session's spend, its subagents' included, and its limit; with a limit on a session that started others, the
1954
+ * team's spend, which is what counts against it.
1955
+ */
1956
+ function spendNow() {
1957
+ const { view } = store.state;
1958
+ const spend = view.conversation?.spend;
1959
+
1960
+ return { spent: spend?.spent ?? view.stats?.cost ?? 0, budget: spend?.budget };
1961
+ }
1962
+
1963
+ defineItem("status", {
1964
+ id: "core:spend",
1965
+ label: "Spend",
1966
+ order: 600,
1967
+ render() {
1968
+ const { spent, budget } = spendNow();
1969
+
1970
+ return html`<span class=${budget !== undefined && spent >= budget ? "warn" : ""}>
1971
+ <span class="num">
1972
+ $${spent.toFixed(2)} ${budget !== undefined ? `/$${budget.toFixed(2)}` : ""}
1973
+ </span>
1974
+ </span>`;
1975
+ },
1976
+ detail() {
1977
+ const { spent, budget } = spendNow();
1978
+
1979
+ return `$${spent.toFixed(2)} spent${budget !== undefined ? ` of $${budget.toFixed(2)}` : ""}`;
1980
+ },
1981
+ });
1982
+
1983
+ /** How many commands the open session runs in the background now (the server's session list counts them). */
1984
+ function backgroundNow() {
1985
+ const { sessions, conversationId } = store.state;
1986
+
1987
+ return sessions.find((session) => session.id === conversationId)?.background ?? 0;
1988
+ }
1989
+
1990
+ const backgroundTitle = (count) =>
1991
+ `${count} ${count === 1 ? "command runs" : "commands run"} in the background: open Running now to see or stop ${count === 1 ? "it" : "them"}`;
1992
+
1993
+ defineItem("status", {
1994
+ id: "core:background",
1995
+ label: "Background tasks",
1996
+ order: 650,
1997
+ render() {
1998
+ const count = backgroundNow();
1999
+
2000
+ return (
2001
+ count > 0 &&
2002
+ html`<button
2003
+ class="background-now"
2004
+ aria-label=${backgroundTitle(count)}
2005
+ title=${backgroundTitle(count)}
2006
+ onClick=${() => openSheet({ type: "running" })}
2007
+ >
2008
+ <span class="dot" aria-hidden="true"></span>
2009
+ <span class="num">${count}</span>
2010
+ <span class="word">${" "}in background</span>
2011
+ </button>`
2012
+ );
2013
+ },
2014
+ detail() {
2015
+ const count = backgroundNow();
2016
+
2017
+ return count > 0 && backgroundTitle(count);
2018
+ },
2019
+ });
2020
+ defineItem("status", {
2021
+ id: "core:guard",
2022
+ label: "Lancet Guard",
2023
+ order: 700,
2024
+ fixed: true,
2025
+ render() {
2026
+ const { guard } = store.state;
2027
+ // On but not loaded: the guard blocks bash, background, write, and edit until it loads or is turned off.
2028
+ const failed = guard?.enabled && guard.available === false;
2029
+
2030
+ if (!guard?.enabled && !guard?.available) {
2031
+ return null;
2032
+ }
2033
+
2034
+ const state = failed ? "failed" : guard.enabled ? "on" : "off";
2035
+
2036
+ return html`<button
2037
+ class=${`guard ${guard.enabled && !failed ? "" : "off"}`}
2038
+ aria-label=${`Lancet Guard ${state}`}
2039
+ title=${guard.detail}
2040
+ onClick=${() => openSheet({ type: "extensions", tab: "installed", show: "built-in" })}
2041
+ >
2042
+ <${Icon} name="shield" size=${11} />
2043
+ <span><span class="word">guard${" "}</span>${state}</span>
2044
+ </button>`;
2045
+ },
2046
+ });
2047
+
2048
+ /** Under the message box: the `status` slot's items, on one row: a narrow one takes shorter forms (`SHORTER`). */
2049
+ function StatusLine() {
2050
+ const line = useRef(null);
2051
+ const items = slotItems("status");
2052
+ const parts = items.map(({ node }) => node);
2053
+ // What each item says, for a tap on the line: a touch screen shows no tooltips.
2054
+ const details = items.map(({ detail }) => detail).filter(Boolean);
2055
+
2056
+ useStatusFit(line);
2057
+
2058
+ // A tap on the line says what it shows (the guard's pill has its own); with a mouse, the tooltips do.
2059
+ const explain = (event) => {
2060
+ if (coarse && !event.target.closest("button")) {
2061
+ notify("info", details.join(" · "));
2062
+ }
2063
+ };
2064
+
2065
+ return html`<div class="status-line" data-part="status-line" ref=${line} onClick=${explain}>
2066
+ ${parts}
2067
+ </div>`;
2068
+ }