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,1217 @@
1
+ // PiP, "Pi in Pocket": the owner's assistant, in a small window over whatever is open. It stays out of the way until
2
+ // called: Alt+A, the rail's PiP button, the places, the launcher, or `/pip`; and a small mark in the corner shows only
3
+ // while PiP works, or has something new. The panel watches PiP's conversation through a view of its own (`pipview`
4
+ // events), so the session behind it stays as it was.
5
+ import { useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
6
+ import { followUpText } from "./artifact-bridge.js";
7
+ import { useBack } from "./back.js";
8
+ import { boxKey, keyBox } from "./box-keys.js";
9
+ import { useDragToClose } from "./gestures.js";
10
+ import { createPipDraft } from "./pip-attachments.js";
11
+ import { usePipResize } from "./pip-window.js";
12
+ import { api, attempt, isRow, navigate, notify, openSheet, store, uid } from "./store.js";
13
+ import { spendTap } from "./taps.js";
14
+ import { memoryAvailable, useMemory } from "./sheets/memory.js";
15
+ import { itemsOf, says, summarize } from "./turns.js";
16
+ import {
17
+ contextLevel,
18
+ entryImageUrl,
19
+ fileUrl,
20
+ formatBytes,
21
+ formatTokens,
22
+ html,
23
+ Icon,
24
+ Markdown,
25
+ modelLabel,
26
+ railState,
27
+ readable,
28
+ Spinner,
29
+ splitAttachments,
30
+ Thumb,
31
+ usePresence,
32
+ } from "./ui.js";
33
+ import { MicButton, useDictation } from "./voice.js";
34
+
35
+ const OPEN_KEY = "pocket.pip";
36
+ const SEEN_KEY = "pocket.pip.seen";
37
+ const DRAFT_KEY = "pocket.pip.draft";
38
+ // Image previews and in-flight work outlive the panel, but never their PiP/account scope.
39
+ const composerDraft = createPipDraft({
40
+ loadText: () => localStorage.getItem(DRAFT_KEY) ?? "",
41
+ saveText: (text) => {
42
+ if (text === "") {
43
+ localStorage.removeItem(DRAFT_KEY);
44
+ } else {
45
+ localStorage.setItem(DRAFT_KEY, text);
46
+ }
47
+ },
48
+ upload: (id, file) => api(`c/${id}/upload?name=${encodeURIComponent(file.name)}`, file),
49
+ onError: (message) => notify("error", message),
50
+ });
51
+ const syncDraftScope = (state) =>
52
+ composerDraft.scope(
53
+ // Before the first hello, a signed-out/unknown bootstrap is not this tab logging out.
54
+ state.me === undefined || (state.me === null && !state.server)
55
+ ? undefined
56
+ : (state.me?.id ?? null),
57
+ state.pip?.id,
58
+ );
59
+
60
+ syncDraftScope(store.state);
61
+ /** How many of PiP's newest rows the panel shows: it is for the moment, and the full conversation is a tap away. */
62
+ const ROWS = 80;
63
+ /** Below this width the panel is a sheet from the bottom edge; above it, a window in the corner. */
64
+ const NARROW = matchMedia("(max-width: 699px)");
65
+ const REPORT = "[report] ";
66
+ /**
67
+ * What came from outside, as PiP gets it: a post to one of the person's webhooks (`hooks.ts`), or what happened on a
68
+ * repository they watch (`repo-watches.ts`). Which one, then the instructions and what came.
69
+ */
70
+ const WEBHOOK = /^\[via webhook ([^\]\n]{1,300})\] /;
71
+ const REPO_WATCH = /^\[via watch ([^\]\n]{1,300})\] /;
72
+
73
+ /**
74
+ * A webhook's post or a watch's news for reading: the person's instructions, and what came as plain text (never
75
+ * Markdown: it is anyone's), without the note to PiP about it.
76
+ */
77
+ function post(text) {
78
+ const body = text.replace(
79
+ /\n?What came between <(?:webhook-payload|github-event)> tags[^\n]*$/,
80
+ "",
81
+ );
82
+ const data = /<(webhook-payload|github-event)[^>]*>\n?([\s\S]*?)\n?<\/\1>/.exec(body);
83
+
84
+ return data
85
+ ? { text: body.slice(0, data.index).trim(), data: readable(data[2]) }
86
+ : { text: body, data: null };
87
+ }
88
+
89
+ const SCHEDULED = "[scheduled] ";
90
+
91
+ const INTRO =
92
+ "I keep an eye on your sessions and repositories: ask what’s going on, start new work, have me check back later, or watch a repository and act when something happens.";
93
+
94
+ /** Things to ask PiP on its first open: sent at once, or (ending in "…") put in the box to finish. */
95
+ const SUGGESTIONS = [
96
+ "What needs me?",
97
+ "What happened today?",
98
+ "Start a session to …",
99
+ "Every weekday at 9:00, tell me what changed overnight",
100
+ "When CI fails on main in …",
101
+ ];
102
+
103
+ /** The server lets this person have a PiP: the owner, while its extension is on. */
104
+ export const pipAvailable = () => store.state.server?.pip === true;
105
+
106
+ let seq = 0;
107
+ /** The connection the panel's last "open" went to: a new one (a reconnect) is told again. */
108
+ let toldConnection = null;
109
+ /** The server's answer to the last "open": PiP's state, with its conversation's id. */
110
+ let opening = null;
111
+
112
+ /** Tell the server whether this tab's panel shows: while it does, the server sends PiP's conversation. */
113
+ function tellServer(on) {
114
+ const connection = store.state.streamId;
115
+
116
+ if (!connection) {
117
+ return Promise.resolve(null);
118
+ }
119
+
120
+ toldConnection = on ? connection : null;
121
+ const asked = api("pip", { connection, on, seq: ++seq }).then(
122
+ (answer) => {
123
+ if (answer.pip) {
124
+ store.set({ pip: answer.pip });
125
+ }
126
+
127
+ return answer.pip ?? null;
128
+ },
129
+ (error) => {
130
+ if (on) {
131
+ closePip();
132
+ notify("error", error.message ?? String(error));
133
+ }
134
+
135
+ return null;
136
+ },
137
+ );
138
+
139
+ if (on) {
140
+ opening = asked;
141
+ }
142
+
143
+ return asked;
144
+ }
145
+
146
+ // A reconnect (or the first connection, with the panel kept open across a reload) gets the panel's view again; PiP
147
+ // turned off in Extensions closes the panel.
148
+ store.subscribe((state) => {
149
+ syncDraftScope(state);
150
+
151
+ if (!state.pipOpen) {
152
+ return;
153
+ }
154
+
155
+ if (state.server && !pipAvailable()) {
156
+ closePip();
157
+ } else if (state.streamId && state.streamId !== toldConnection) {
158
+ tellServer(true);
159
+ }
160
+ });
161
+
162
+ // A PiP notification tapped while a window is open: the worker asks that window for the panel (`sw.js`).
163
+ navigator.serviceWorker?.addEventListener("message", (event) => {
164
+ if (event.data?.type === "pocket.pip") {
165
+ openPip();
166
+ }
167
+ });
168
+
169
+ /** PiP's answers seen up to now: what the panel last showed, by the server's clock. */
170
+ function markSeen() {
171
+ const ended = store.state.pip?.endedAt;
172
+
173
+ if (ended !== undefined && ended > Number(localStorage.getItem(SEEN_KEY) ?? 0)) {
174
+ localStorage.setItem(SEEN_KEY, String(ended));
175
+ }
176
+ }
177
+
178
+ /** PiP answered since this browser last looked, and is not at work. */
179
+ export function pipUnread(state = store.state) {
180
+ const pip = state.pip;
181
+
182
+ return Boolean(
183
+ pip &&
184
+ !state.pipOpen &&
185
+ !pip.busy &&
186
+ pip.endedAt !== undefined &&
187
+ pip.endedAt > Number(localStorage.getItem(SEEN_KEY) ?? 0),
188
+ );
189
+ }
190
+
191
+ /** Open the panel; with `text`, put it in PiP's message box. */
192
+ export function openPip(text) {
193
+ if (!pipAvailable()) {
194
+ return;
195
+ }
196
+
197
+ if (text) {
198
+ store.set({ pipDraft: { text, n: (store.state.pipDraft?.n ?? 0) + 1 } });
199
+ }
200
+
201
+ if (store.state.pipOpen) {
202
+ focusComposer();
203
+
204
+ return;
205
+ }
206
+
207
+ sessionStorage.setItem(OPEN_KEY, "1");
208
+ // The subscriber above tells the server, from inside this `set`: once, not twice.
209
+ store.set({ pipOpen: true, launcher: false, drawer: false });
210
+ }
211
+
212
+ export function closePip() {
213
+ if (!store.state.pipOpen) {
214
+ return;
215
+ }
216
+
217
+ sessionStorage.removeItem(OPEN_KEY);
218
+ markSeen();
219
+ store.set({ pipOpen: false });
220
+ tellServer(false);
221
+ }
222
+
223
+ export const togglePip = () => (store.state.pipOpen ? closePip() : openPip());
224
+
225
+ /** Put `text` in PiP's box, after what is there, and open the panel. */
226
+ function draftPip(text) {
227
+ const draft = localStorage.getItem(DRAFT_KEY)?.trim();
228
+
229
+ openPip(draft ? `${draft}\n\n${text}` : text);
230
+ }
231
+
232
+ /** Send PiP a message from anywhere (`/pip …`), and open the panel to show what it says; true when it went. */
233
+ export async function askPip(text) {
234
+ if (!pipAvailable()) {
235
+ notify("error", "PiP is not on here.");
236
+
237
+ return false;
238
+ }
239
+
240
+ const account = store.state.me?.id;
241
+
242
+ openPip();
243
+ const pip = store.state.pip ?? (await opening);
244
+
245
+ if (account !== store.state.me?.id) {
246
+ return false;
247
+ }
248
+
249
+ if (!pip) {
250
+ notify("error", "PiP is not ready yet: your message waits in its box.");
251
+ }
252
+
253
+ // Not sent: the words wait in PiP's box rather than be lost (`send` said why), after what was there already.
254
+ if (pip && (await send(pip.id, text, false))) {
255
+ return true;
256
+ }
257
+
258
+ if (account === store.state.me?.id && (!pip || store.state.pip?.id === pip.id)) {
259
+ draftPip(text);
260
+ }
261
+
262
+ return false;
263
+ }
264
+
265
+ const PIP_UNAVAILABLE = "PiP is not available";
266
+
267
+ /**
268
+ * What `pocket.pip.ask` does for the browser module `source` names: put its text in PiP's box for the person to read,
269
+ * edit, and send; or, with `send` and only just after a tap or a key press, send it as the person's own message. The
270
+ * text starts with where it came from, as an artifact's follow-up does, so it never reads as a command. The answer says
271
+ * why nothing happened, or whether the message went (`sent` is false when it waits in the box).
272
+ */
273
+ export async function askPipFrom(source, text, send) {
274
+ if (!pipAvailable()) {
275
+ return { ok: false, reason: PIP_UNAVAILABLE };
276
+ }
277
+
278
+ const words = followUpText(text.trim(), undefined, source);
279
+
280
+ if (!send) {
281
+ draftPip(words);
282
+
283
+ return { ok: true, sent: false };
284
+ }
285
+
286
+ if (!spendTap()) {
287
+ return { ok: false, reason: "Sending needs a click or a key press just before" };
288
+ }
289
+
290
+ return { ok: true, sent: await askPip(words) };
291
+ }
292
+
293
+ /** Send PiP a message; false when it did not go (a notice says why). PiP made just now is waited for. */
294
+ async function send(id, text, busy, attachments = []) {
295
+ const account = store.state.me?.id;
296
+ const target = id ?? store.state.pip?.id ?? (await opening)?.id;
297
+
298
+ if (account !== store.state.me?.id || (id !== undefined && store.state.pip?.id !== id)) {
299
+ return false;
300
+ }
301
+
302
+ if (target === undefined) {
303
+ notify("error", "PiP is not ready yet. Try again in a moment.");
304
+
305
+ return false;
306
+ }
307
+
308
+ const sent = await attempt(() =>
309
+ api(`c/${target}/submit`, {
310
+ text,
311
+ ...(attachments.length > 0 ? { attachments } : {}),
312
+ requestId: uid(),
313
+ // Words for PiP while it works change what it does now, rather than wait for it.
314
+ ...(busy ? { mode: "steer" } : {}),
315
+ }),
316
+ );
317
+
318
+ return sent !== undefined;
319
+ }
320
+
321
+ /**
322
+ * Compact PiP's context: older messages become a summary PiP writes without what came from outside (`pip-compact.ts`).
323
+ * `focus`, the person's words, is what the summary should keep in mind. A notice says when it is done.
324
+ */
325
+ function compactPip(id, focus) {
326
+ return attempt(() => api(`c/${id}/compact`, focus ? { instructions: focus } : {}));
327
+ }
328
+
329
+ /** `/compact`, or `/compact what to keep in mind`, typed in PiP's box. */
330
+ const COMPACT = /^\/compact(?:\s+([\s\S]*))?$/;
331
+
332
+ /** How close PiP is to its own compaction limit, never beyond the model's context window. */
333
+ function PipContext({ stats, window }) {
334
+ if (!window || stats?.contextTokens === undefined) {
335
+ return null;
336
+ }
337
+
338
+ const used = stats.contextTokens;
339
+ const at = store.state.server?.pipCompactAt;
340
+ const limit = at > 0 ? Math.min(at, window) : window;
341
+ const percent = Math.min(100, Math.round((used / limit) * 100));
342
+ const about = stats.contextEstimated ? "~" : "";
343
+ const tokens = `${about}${formatTokens(used)} of ${formatTokens(limit)} tokens in PiP's context.`;
344
+ const when =
345
+ at > window
346
+ ? `PiP's idle compaction limit is ${formatTokens(at)} tokens.`
347
+ : at > 0
348
+ ? `PiP compacts itself above ${formatTokens(at)} once idle.`
349
+ : "Compact it when it grows.";
350
+ const cap = at > window ? " The meter is capped at the model's context window." : "";
351
+ const title = `${tokens} ${when}${cap}`;
352
+
353
+ return html`<span
354
+ class="pip-context"
355
+ role="img"
356
+ aria-label=${`Context ${about}${percent}% full`}
357
+ title=${title}
358
+ >
359
+ <span class=${`meter ${contextLevel(percent)}`}><span style=${`width:${percent}%`}></span></span>
360
+ ${about}${percent}%
361
+ </span>`;
362
+ }
363
+
364
+ function focusComposer() {
365
+ requestAnimationFrame(() => document.querySelector(".pip-composer textarea")?.focus());
366
+ }
367
+
368
+ /** A message in PiP's conversation without the "[from: Name]" a server with several people puts first. */
369
+ const written = (text) => text.replace(/^\[from: [^\]\n]{1,60}\] /, "");
370
+
371
+ /**
372
+ * PiP's words with bare session addresses (`/s/12`, as reports and tool results write them) made links named after
373
+ * their sessions. Links already written stay as they are.
374
+ */
375
+ function linkSessions(text) {
376
+ // What sessions said comes fenced for PiP (`pip.ts`); people read it as it is.
377
+ text = text.replace(/\n?<\/?session-output>\n?/g, "\n");
378
+ // `“Title” (/s/12)`, as reports name a session: one link.
379
+ const named = text.replace(/“([^”\n[\]]{1,120})” \(\/s\/(\d+)\)/g, "[$1](/s/$2)");
380
+
381
+ return named.replace(/(?<!\]\()(?<![\w/.])\/s\/(\d+)\b(?![\w/])/g, (_, id) => {
382
+ const title = store.state.sessions.find((session) => session.id === Number(id))?.title;
383
+ const label = (title ?? `/s/${id}`).replace(/[[\]]/g, "");
384
+
385
+ return `[${label}](/s/${id})`;
386
+ });
387
+ }
388
+
389
+ /** The session a link in PiP's words opens: `/s/12`, written whole or as an address of this app. */
390
+ function sessionOf(anchor) {
391
+ const href = anchor.getAttribute("href") ?? "";
392
+ const match = /^(?:https?:\/\/[^/]+)?\/s\/(\d+)\/?$/.exec(href);
393
+
394
+ return match && (!/^https?:/.test(href) || new URL(href).origin === location.origin)
395
+ ? Number(match[1])
396
+ : null;
397
+ }
398
+
399
+ // ─── The panel ──────────────────────────────────────────────────────────────
400
+
401
+ /** A report from a session PiP follows, or a webhook's post (with what came as `data`): folded until opened. */
402
+ function Report({ text, label = "Report", data = null, conversationId }) {
403
+ const [open, setOpen] = useState(false);
404
+
405
+ return html`<div class=${`pip-report ${open ? "open" : ""}`}>
406
+ <button
407
+ type="button"
408
+ class="pip-report-head"
409
+ aria-expanded=${open}
410
+ onClick=${() => setOpen(!open)}
411
+ >
412
+ <${Icon} name="pulse" size=${13} />
413
+ <span>${label}</span>
414
+ <${Icon} name="down" size=${13} class="pip-report-fold" />
415
+ </button>
416
+ <${Markdown}
417
+ text=${linkSessions(text)}
418
+ class="pip-report-text"
419
+ conversationId=${conversationId}
420
+ />
421
+ ${data !== null && html`<pre class="pip-report-data">${data}</pre>`}
422
+ </div>`;
423
+ }
424
+
425
+ /**
426
+ * A message's list of attached files (`splitAttachments`). Uploaded names can contain commas or parentheses: find the
427
+ * name repeated at the end of its saved path.
428
+ */
429
+ function attachedFiles(block) {
430
+ if (block === undefined) {
431
+ return [];
432
+ }
433
+
434
+ return block.split("\n").flatMap((line) => {
435
+ const suffix = /^- (.*), ([^,]*), (\d+) bytes\)$/.exec(line);
436
+
437
+ if (!suffix) {
438
+ return [];
439
+ }
440
+
441
+ const candidates = [...suffix[1].matchAll(/ \(/g)].map((separator) => ({
442
+ path: suffix[1].slice(0, separator.index),
443
+ name: suffix[1].slice(separator.index + 2),
444
+ mime: suffix[2],
445
+ }));
446
+ const file = candidates.find((candidate) => candidate.path.endsWith(candidate.name));
447
+
448
+ return file ? [file] : [];
449
+ });
450
+ }
451
+
452
+ /** One of the panel's rows: a message, a report, a group of PiP's calls, or its words. */
453
+ function Item({ item, last, busy, conversationId }) {
454
+ if (item.type === "row") {
455
+ const entry = item.entry;
456
+
457
+ if (entry.kind === "user") {
458
+ // Reports, posts, and scheduled messages whole: what came from outside may hold anything, an attachment
459
+ // heading too, and is read only as the plain data it is.
460
+ const body = written(entry.text);
461
+
462
+ if (body.startsWith(REPORT)) {
463
+ return html`<${Report}
464
+ text=${body.slice(REPORT.length)}
465
+ conversationId=${conversationId}
466
+ />`;
467
+ }
468
+
469
+ const hook = WEBHOOK.exec(body);
470
+ const watched = hook ? null : REPO_WATCH.exec(body);
471
+ const outside = hook ?? watched;
472
+
473
+ if (outside) {
474
+ const posted = post(body.slice(outside[0].length));
475
+
476
+ return html`<${Report}
477
+ label=${`${watched ? "GitHub" : "Webhook"}: ${outside[1]}`}
478
+ text=${posted.text}
479
+ data=${posted.data}
480
+ conversationId=${conversationId}
481
+ />`;
482
+ }
483
+
484
+ if (body.startsWith(SCHEDULED)) {
485
+ return html`<div class="pip-event">
486
+ <${Icon} name="pulse" size=${13} />
487
+ <span>${body.slice(SCHEDULED.length)}</span>
488
+ </div>`;
489
+ }
490
+
491
+ const [text, block] = splitAttachments(body);
492
+ // Uploaded pictures also remain readable when the chosen model cannot take inline images.
493
+ const files = attachedFiles(block);
494
+ const pictures = files.filter((file) => file.mime.startsWith("image/"));
495
+ const others = files.filter((file) => !pictures.includes(file));
496
+
497
+ return html`<div class="pip-you">
498
+ ${text && html`<div>${text}</div>`}
499
+ ${
500
+ others.length > 0 &&
501
+ html`<div class="attachments">
502
+ ${others.map((file) => html`<span class="chip">📎 ${file.name}</span>`)}
503
+ </div>`
504
+ }
505
+ ${
506
+ (pictures.length > 0 || entry.images > 0) &&
507
+ html`<div class="thumbs">
508
+ ${
509
+ pictures.length > 0
510
+ ? pictures.map(
511
+ (picture) => html`<${Thumb}
512
+ src=${fileUrl(picture.path, conversationId)}
513
+ alt=${picture.name}
514
+ />`,
515
+ )
516
+ : Array.from(
517
+ { length: entry.images },
518
+ (_, index) => html`<${Thumb}
519
+ src=${entryImageUrl(entry.id, index, conversationId)}
520
+ alt=${`Image ${index + 1}`}
521
+ />`,
522
+ )
523
+ }
524
+ </div>`
525
+ }
526
+ </div>`;
527
+ }
528
+
529
+ const line =
530
+ entry.kind === "reset"
531
+ ? "Fresh start"
532
+ : entry.kind === "compaction"
533
+ ? "Earlier messages summarized"
534
+ : entry.kind === "note"
535
+ ? `${entry.name} ${entry.text}`
536
+ : null;
537
+
538
+ return line && html`<div class="pip-event"><span>${line}</span></div>`;
539
+ }
540
+
541
+ // A page it showed in a reply (`artifact_inline`): in this panel, a line like its other work.
542
+ if (item.type === "inline") {
543
+ return html`<div class="pip-steps">
544
+ <span class="pip-tick"><${Icon} name="check" size=${10} /></span>
545
+ <span>${summarize([item.step], false)}</span>
546
+ </div>`;
547
+ }
548
+
549
+ if (item.type === "activity") {
550
+ const thinking =
551
+ item.steps.at(-1)?.streaming && item.steps.at(-1).block.type === "thinking";
552
+ const working = busy && last;
553
+
554
+ return html`<div class=${`pip-steps ${working ? "working" : ""}`}>
555
+ ${working ? html`<${Spinner} hidden=${true} />` : html`<span class="pip-tick"><${Icon} name="check" size=${10} /></span>`}
556
+ <span>${summarize(item.steps, thinking)}</span>
557
+ </div>`;
558
+ }
559
+
560
+ if (item.type === "reply") {
561
+ const text = item.blocks.map((each) => each.block.text).join("\n\n");
562
+ const growing = item.blocks.some((each) => each.growing);
563
+ const entry = item.entry;
564
+
565
+ return html`<div class="pip-reply">
566
+ ${
567
+ text.trim() !== "" &&
568
+ html`<${Markdown}
569
+ text=${linkSessions(text)}
570
+ cache=${!growing}
571
+ conversationId=${conversationId}
572
+ />`
573
+ }
574
+ ${entry?.stopReason === "aborted" && html`<div class="pip-event"><span>Stopped</span></div>`}
575
+ ${
576
+ entry?.stopReason === "error" &&
577
+ html`<div class="pip-error">${entry.error ?? "The model request failed."}</div>`
578
+ }
579
+ </div>`;
580
+ }
581
+
582
+ return null;
583
+ }
584
+
585
+ function Welcome({ id, name, hasModel }) {
586
+ const first = (name ?? "").split(/\s+/)[0];
587
+
588
+ return html`<div class="pip-welcome">
589
+ <p class="pip-hello">Hi${first ? ` ${first}` : ""}. I’m PiP.</p>
590
+ <p class="pip-intro">${INTRO}</p>
591
+ ${
592
+ !hasModel &&
593
+ html`<p class="pip-intro">
594
+ <button
595
+ type="button"
596
+ class="button small"
597
+ onClick=${() => openSheet({ type: "model", pipId: id })}
598
+ >
599
+ Choose a model to use these suggestions
600
+ </button>
601
+ </p>`
602
+ }
603
+ <div class="pip-chips">
604
+ ${SUGGESTIONS.map(
605
+ (suggestion) => html`<button
606
+ type="button"
607
+ class="pip-chip"
608
+ key=${suggestion}
609
+ disabled=${!hasModel && !suggestion.endsWith("…")}
610
+ onClick=${() =>
611
+ suggestion.endsWith("…")
612
+ ? openPip(suggestion.slice(0, -1))
613
+ : send(id, suggestion, false)}
614
+ >
615
+ ${suggestion}
616
+ </button>`,
617
+ )}
618
+ </div>
619
+ </div>`;
620
+ }
621
+
622
+ function Composer({ id, busy }) {
623
+ const [saved, setSaved] = useState(() => {
624
+ composerDraft.syncText();
625
+
626
+ return composerDraft.state;
627
+ });
628
+ const { text, files, pending } = saved;
629
+ const ref = useRef(null);
630
+ const picker = useRef(null);
631
+ const draft = store.state.pipDraft;
632
+ const change = composerDraft.changeText;
633
+ const uploading = files.some((file) => file.state === "uploading");
634
+ const hasMessage = text.trim() !== "" || files.length > 0;
635
+ const sendDisabled =
636
+ !hasMessage || (uploading && !COMPACT.test(text.trim())) || Boolean(pending);
637
+
638
+ useLayoutEffect(() => {
639
+ const unsubscribe = composerDraft.subscribe(setSaved);
640
+
641
+ setSaved(composerDraft.state);
642
+
643
+ return unsubscribe;
644
+ }, []);
645
+
646
+ const fit = () => {
647
+ const box = ref.current;
648
+
649
+ if (box) {
650
+ box.style.height = "auto";
651
+ box.style.height = `${Math.min(box.scrollHeight, 160)}px`;
652
+ }
653
+ };
654
+
655
+ // PiP's box takes Alt+V while it shows, over the session's.
656
+ const dictation = useDictation(ref, change, { top: true });
657
+
658
+ useLayoutEffect(fit, [text]);
659
+ // A phone's keyboard would cover the panel as it opens: there, the box waits for a tap. Elsewhere it takes the focus
660
+ // as it mounts, in the same task as the key that opened it, so the next keys land here.
661
+ useLayoutEffect(() => {
662
+ if (!NARROW.matches) {
663
+ ref.current?.focus({ preventScroll: true });
664
+ }
665
+ }, []);
666
+ useEffect(() => {
667
+ if (draft) {
668
+ change(draft.text);
669
+ ref.current?.focus();
670
+ // Used: opened again later, the box keeps what was typed since.
671
+ store.set({ pipDraft: null });
672
+ }
673
+ }, [draft?.n]);
674
+
675
+ const submit = async (event) => {
676
+ event?.preventDefault();
677
+ // Read the durable-in-this-tab draft, not a render's text or an old panel's queue.
678
+ const message = composerDraft.state.text.trim();
679
+ const compact = COMPACT.exec(message);
680
+
681
+ if (message === "" && composerDraft.state.files.length === 0) {
682
+ return;
683
+ }
684
+
685
+ if (compact && id === undefined) {
686
+ notify("error", "PiP is not ready yet. Try again in a moment.");
687
+
688
+ return;
689
+ }
690
+
691
+ const token = composerDraft.begin(Boolean(compact));
692
+
693
+ if (!token) {
694
+ return;
695
+ }
696
+
697
+ // What shows is what goes: words still coming would land in the emptied box.
698
+ dictation.stop(true);
699
+ let success = false;
700
+
701
+ try {
702
+ // Compact never sends or removes the attachments waiting in the box.
703
+ success = compact
704
+ ? (await compactPip(id, compact[1]?.trim())) !== undefined
705
+ : await send(
706
+ id,
707
+ message,
708
+ busy,
709
+ token.files.map((file) => file.attachment),
710
+ );
711
+ } finally {
712
+ composerDraft.finish(token, success);
713
+ }
714
+ };
715
+
716
+ const onPaste = (event) => {
717
+ const pasted = [...(event.clipboardData?.files ?? [])];
718
+
719
+ if (pasted.length === 0) {
720
+ return; // Normal text paste retains the browser's caret/selection behavior.
721
+ }
722
+
723
+ event.preventDefault();
724
+ composerDraft.addFiles(pasted);
725
+ const words = event.clipboardData?.getData("text/plain") ?? "";
726
+ const box = event.currentTarget;
727
+
728
+ if (words) {
729
+ const at = box.selectionStart;
730
+ const end = box.selectionEnd;
731
+ const current = composerDraft.state.text;
732
+
733
+ change(`${current.slice(0, at)}${words}${current.slice(end)}`);
734
+ requestAnimationFrame(() =>
735
+ box.setSelectionRange(at + words.length, at + words.length),
736
+ );
737
+ }
738
+ };
739
+
740
+ return html`<div
741
+ class="pip-composer-wrap"
742
+ onDragOver=${(event) => {
743
+ if ([...(event.dataTransfer?.types ?? [])].includes("Files")) {
744
+ event.preventDefault();
745
+ }
746
+ }}
747
+ onDrop=${(event) => {
748
+ const dropped = [...(event.dataTransfer?.files ?? [])];
749
+
750
+ if (dropped.length > 0) {
751
+ event.preventDefault();
752
+ composerDraft.addFiles(dropped);
753
+ }
754
+ }}
755
+ >
756
+ ${
757
+ files.length > 0 &&
758
+ html`<div class="pip-attachments" aria-label="Files attached to PiP">
759
+ ${files.map(
760
+ (file) => html`<div class="pip-attachment" key=${file.key}>
761
+ ${file.preview && html`<${Thumb} src=${file.preview} alt=${file.name} />`}
762
+ <span class="pip-attachment-name">${file.name}</span>
763
+ <span class="muted">${formatBytes(file.size)}</span>
764
+ ${
765
+ file.state === "uploading" &&
766
+ html`<${Spinner} label=${`Uploading ${file.name}`} />`
767
+ }
768
+ <button
769
+ type="button"
770
+ class="icon-button pip-attachment-remove"
771
+ aria-label=${`Remove ${file.name}`}
772
+ onClick=${() => composerDraft.removeFile(file.key)}
773
+ >
774
+ <${Icon} name="close" size=${14} />
775
+ </button>
776
+ </div>`,
777
+ )}
778
+ </div>`
779
+ }
780
+ <form class="pip-composer" onSubmit=${submit}>
781
+ <input
782
+ class="pip-file-picker"
783
+ ref=${picker}
784
+ type="file"
785
+ multiple
786
+ hidden
787
+ disabled=${id === undefined}
788
+ onChange=${(event) => {
789
+ composerDraft.addFiles([...(event.currentTarget.files ?? [])]);
790
+ event.currentTarget.value = "";
791
+ }}
792
+ />
793
+ <button
794
+ type="button"
795
+ class="icon-button pip-attach"
796
+ aria-label="Attach files to PiP"
797
+ title="Attach files. Images need an image-capable model to be read inline."
798
+ disabled=${id === undefined}
799
+ onClick=${() => picker.current?.click()}
800
+ >
801
+ <${Icon} name="clip" size=${18} />
802
+ </button>
803
+ <textarea
804
+ ref=${ref}
805
+ rows="1"
806
+ value=${text}
807
+ placeholder=${dictation.listening ? "Listening…" : busy ? "Tell PiP more…" : "Ask PiP…"}
808
+ aria-label="Message to PiP"
809
+ enterkeyhint="send"
810
+ onInput=${(event) => change(event.currentTarget.value)}
811
+ onPaste=${onPaste}
812
+ onKeyDown=${(event) => {
813
+ // A module's key (`pocket.composerKey`) comes first, as in the session's box.
814
+ const keyed = keyBox(event.currentTarget, "pip", (value, start, end) => {
815
+ change(value);
816
+ requestAnimationFrame(() => ref.current?.setSelectionRange(start, end));
817
+ });
818
+
819
+ if (boxKey(event, keyed)) {
820
+ event.preventDefault();
821
+
822
+ return;
823
+ }
824
+
825
+ if (
826
+ event.key === "Enter" &&
827
+ !event.shiftKey &&
828
+ !event.isComposing &&
829
+ event.keyCode !== 229
830
+ ) {
831
+ submit(event);
832
+ }
833
+ }}
834
+ ></textarea>
835
+ <${MicButton} dictation=${dictation} class="pip-mic" size=${18} />
836
+ ${
837
+ busy && !hasMessage && !pending
838
+ ? html`<button
839
+ type="button"
840
+ class="icon-button pip-send"
841
+ aria-label="Stop PiP"
842
+ title="Stop"
843
+ onClick=${() => attempt(() => api(`c/${id}/abort`, {}))}
844
+ >
845
+ <${Icon} name="stop" size=${18} />
846
+ </button>`
847
+ : html`<button
848
+ type="submit"
849
+ class="icon-button pip-send"
850
+ aria-label="Send to PiP"
851
+ disabled=${sendDisabled}
852
+ >
853
+ <${Icon} name="send" size=${18} />
854
+ </button>`
855
+ }
856
+ </form>
857
+ </div>`;
858
+ }
859
+
860
+ /** The owner's private review queue, not just the memories that apply in the conversation behind PiP. */
861
+ function PendingMemories({ id }) {
862
+ const data = useMemory(id, true);
863
+ const count = data?.pendingAll === true ? data.lessons.length : null;
864
+ const hint = data?.restartRequired
865
+ ? "Restart required"
866
+ : count === null
867
+ ? "Loading…"
868
+ : `${count} pending`;
869
+
870
+ return html`<div class="pip-memory">
871
+ <button
872
+ type="button"
873
+ class="button small ghost"
874
+ aria-label="Pending memories"
875
+ aria-describedby="pip-memory-count"
876
+ onClick=${() => {
877
+ closePip();
878
+ openSheet({ type: "memory", conversationId: id, pendingOnly: true });
879
+ }}
880
+ >
881
+ <span>Pending memories</span>
882
+ <span
883
+ id="pip-memory-count"
884
+ class=${`pip-memory-count ${count > 0 ? "waiting" : ""}`}
885
+ aria-live="polite"
886
+ aria-atomic="true"
887
+ >
888
+ ${hint}
889
+ </span>
890
+ </button>
891
+ </div>`;
892
+ }
893
+
894
+ /** When PiP takes a message that waits: a steer at its next pause, a queued one when it finishes its work. */
895
+ const pendingWhen = (item, busy) =>
896
+ !busy
897
+ ? "Waiting for PiP"
898
+ : item.mode === "steer"
899
+ ? "PiP reads this at its next pause"
900
+ : "PiP reads this when it finishes";
901
+
902
+ /** Who sent a message, as the server writes it at the start when several people use Pi (`FROM_PREFIX`). */
903
+ const FROM = /^\[from: [^\]\n]{1,60}\] /;
904
+
905
+ function PipPanel({ leaving, scrim }) {
906
+ const { pip, pipView: view, me } = store.state;
907
+ const ref = useRef(null);
908
+ const body = useRef(null);
909
+ const pinned = useRef(true);
910
+ const id = pip?.id;
911
+ const ready = id !== undefined && view.conversation?.id === id;
912
+ const live = ready ? view.live : { busy: false };
913
+ const rows = ready
914
+ ? view.order
915
+ .map((entryId) => view.entries.get(entryId))
916
+ .filter((entry) => entry && isRow(entry))
917
+ .slice(-ROWS)
918
+ : [];
919
+ // Your messages that wait while PiP works: shown at once, as waiting, until PiP takes them.
920
+ const pending = ready
921
+ ? (view.inbox ?? []).filter(
922
+ (item) => item.by === me?.id && (item.mode === "steer" || item.mode === "followUp"),
923
+ )
924
+ : [];
925
+ const blocks = live.generation?.message?.blocks ?? [];
926
+ const items = itemsOf(rows, blocks.length > 0 ? { kind: "assistant", blocks } : null);
927
+ const speaking = blocks.some(says);
928
+ const busy = live.busy === true;
929
+ const model = modelLabel(view.agent);
930
+ const thinking = view.agent?.thinkingLevel === "off" ? "" : (view.agent?.thinkingLevel ?? "");
931
+ // Calls of PiP's held for approval: the panel cannot answer them, so it says so and leads to where they can be.
932
+ const waiting = ready ? (view.approvals ?? []) : [];
933
+ const compacting = ready && (live.compactions ?? []).length > 0;
934
+ const status =
935
+ waiting.length > 0 ? "needs you" : compacting ? "compacting…" : busy ? "working…" : "";
936
+ // Where the focus was before the panel: read as it first renders, before its box takes the focus.
937
+ const [before] = useState(() => document.activeElement);
938
+
939
+ usePipResize(ref, me?.id);
940
+ useDragToClose(ref, { dir: "down", onClose: closePip, enabled: NARROW.matches, scrim });
941
+ // Focus goes back where it was when the panel closes.
942
+ useEffect(() => {
943
+ const panel = ref.current;
944
+
945
+ return () => {
946
+ const active = document.activeElement;
947
+
948
+ if (
949
+ before instanceof HTMLElement &&
950
+ before.isConnected &&
951
+ (active === document.body || panel?.contains(active))
952
+ ) {
953
+ before.focus({ preventScroll: true });
954
+ }
955
+ };
956
+ }, []);
957
+ // What shows now counts as seen.
958
+ useEffect(markSeen, [pip?.endedAt]);
959
+ // Stay at the newest words while they come, unless someone scrolled up to read.
960
+ useLayoutEffect(() => {
961
+ const box = body.current;
962
+
963
+ if (box && pinned.current) {
964
+ box.scrollTop = box.scrollHeight;
965
+ }
966
+ });
967
+
968
+ const openLink = (event) => {
969
+ const anchor = event.target.closest?.("a[href]");
970
+ const session = anchor ? sessionOf(anchor) : null;
971
+
972
+ if (session === null) {
973
+ return;
974
+ }
975
+
976
+ event.preventDefault();
977
+ navigate(session);
978
+
979
+ // On a phone the session is behind the panel: it steps aside.
980
+ if (NARROW.matches) {
981
+ closePip();
982
+ }
983
+ };
984
+
985
+ return html`<section
986
+ class=${`pip-panel ${leaving ? "leaving" : ""}`}
987
+ data-part="pip"
988
+ data-state=${leaving ? "closing" : undefined}
989
+ ref=${ref}
990
+ role="dialog"
991
+ aria-modal=${NARROW.matches ? "true" : undefined}
992
+ aria-label="PiP, your assistant"
993
+ >
994
+ <div class="pip-resize pip-resize-left" data-pip-resize="left" aria-hidden="true"></div>
995
+ <div class="pip-resize pip-resize-top" data-pip-resize="top" aria-hidden="true"></div>
996
+ <div class="pip-resize pip-resize-corner" data-pip-resize="corner" aria-hidden="true"></div>
997
+ <header class="pip-head">
998
+ <div class="grip"></div>
999
+ <span class=${`pip-mark ${busy ? "working" : ""}`} aria-hidden="true">
1000
+ <${Icon} name="pip" size=${18} />
1001
+ </span>
1002
+ <div class="pip-heading">
1003
+ <div class="pip-title-line">
1004
+ <h2>PiP</h2>
1005
+ <span class="pip-status" aria-live="polite">${status}</span>
1006
+ </div>
1007
+ <button
1008
+ class="model-chip pip-model"
1009
+ disabled=${!ready || busy || compacting}
1010
+ aria-label=${`PiP model: ${model}${thinking ? ` · ${thinking}` : ""}`}
1011
+ title="Change PiP's model and thinking level"
1012
+ onClick=${() => openSheet({ type: "model", pipId: id })}
1013
+ >
1014
+ <span class="model-name">
1015
+ ${model.replace(/^(?:anthropic:\s*)?claude\s+/i, "")}
1016
+ </span>
1017
+ ${thinking && html`<span class="model-level">${thinking}</span>`}
1018
+ </button>
1019
+ </div>
1020
+ ${
1021
+ ready &&
1022
+ html`<${PipContext} stats=${view.stats} window=${view.agent?.contextWindow} />`
1023
+ }
1024
+ <button
1025
+ class="icon-button"
1026
+ aria-label="Compact"
1027
+ title="Compact: PiP keeps a summary of older messages, and reads less each time"
1028
+ disabled=${!ready || busy || compacting || rows.length === 0}
1029
+ onClick=${() => compactPip(id)}
1030
+ >
1031
+ <${Icon} name="compact" size=${18} />
1032
+ </button>
1033
+ <button
1034
+ class="icon-button"
1035
+ aria-label="Start fresh"
1036
+ title="Start fresh: PiP forgets this conversation"
1037
+ disabled=${!ready || busy || rows.length === 0}
1038
+ onClick=${() =>
1039
+ confirm("Start fresh? PiP forgets this conversation; you can still read it.") &&
1040
+ attempt(() => api(`c/${id}/reset`, {}))}
1041
+ >
1042
+ <${Icon} name="reload" size=${18} />
1043
+ </button>
1044
+ <button
1045
+ class="icon-button"
1046
+ aria-label="Open as a conversation"
1047
+ title="Open as a conversation, with every step"
1048
+ disabled=${!ready}
1049
+ onClick=${() => {
1050
+ closePip();
1051
+ navigate(id);
1052
+ }}
1053
+ >
1054
+ <${Icon} name="external" size=${18} />
1055
+ </button>
1056
+ <button class="icon-button" aria-label="Close PiP" title="Close (Esc)" onClick=${closePip}>
1057
+ <${Icon} name="close" size=${18} />
1058
+ </button>
1059
+ </header>
1060
+ <div
1061
+ class="pip-body"
1062
+ ref=${body}
1063
+ onClick=${openLink}
1064
+ onScroll=${(event) => {
1065
+ const box = event.currentTarget;
1066
+
1067
+ pinned.current = box.scrollHeight - box.scrollTop - box.clientHeight < 48;
1068
+ }}
1069
+ >
1070
+ ${
1071
+ !ready
1072
+ ? html`<div class="pip-loading"><${Spinner} label="Waking PiP" /></div>`
1073
+ : rows.length === 0 && !busy
1074
+ ? html`<${Welcome}
1075
+ id=${id}
1076
+ name=${me?.name}
1077
+ hasModel=${Boolean(view.agent?.model)}
1078
+ />`
1079
+ : items.map(
1080
+ (item, index) =>
1081
+ html`<${Item}
1082
+ key=${item.key}
1083
+ item=${item}
1084
+ last=${index === items.length - 1}
1085
+ busy=${busy}
1086
+ conversationId=${id}
1087
+ />`,
1088
+ )
1089
+ }
1090
+ ${
1091
+ ready &&
1092
+ busy &&
1093
+ !speaking &&
1094
+ items.at(-1)?.type !== "activity" &&
1095
+ html`<div class="pip-steps working">
1096
+ <${Spinner} hidden=${true} />
1097
+ <span>Thinking</span>
1098
+ </div>`
1099
+ }
1100
+ ${pending.map(
1101
+ (item) => html`<div class="pip-you pending" key=${`pending-${item.id}`}>
1102
+ <div>${(item.text ?? "").replace(FROM, "")}</div>
1103
+ <div class="pip-pending-line">
1104
+ <span>${pendingWhen(item, busy)}</span>
1105
+ <button
1106
+ type="button"
1107
+ class="pip-pending-withdraw"
1108
+ onClick=${() =>
1109
+ attempt(() => api(`c/${id}/withdraw`, { submissionId: item.id }))}
1110
+ >
1111
+ Withdraw
1112
+ </button>
1113
+ </div>
1114
+ </div>`,
1115
+ )}
1116
+ </div>
1117
+ ${
1118
+ waiting.length > 0 &&
1119
+ html`<div class="pip-approval" role="status">
1120
+ <${Icon} name="shield" size=${14} />
1121
+ <span class="grow">PiP waits for your approval: ${waiting[0].tool}</span>
1122
+ <button
1123
+ type="button"
1124
+ class="button small"
1125
+ onClick=${() => {
1126
+ closePip();
1127
+ navigate(id);
1128
+ }}
1129
+ >
1130
+ Review
1131
+ </button>
1132
+ </div>`
1133
+ }
1134
+ ${
1135
+ ready &&
1136
+ me?.role === "owner" &&
1137
+ memoryAvailable(id) &&
1138
+ html`<${PendingMemories} id=${id} />`
1139
+ }
1140
+ <${Composer} id=${id} busy=${busy} />
1141
+ </section>`;
1142
+ }
1143
+
1144
+ /** The mark in the corner: only while PiP works, or has something new. */
1145
+ function PipBubble() {
1146
+ const { pip } = store.state;
1147
+ const unread = pipUnread();
1148
+ const [kept, leaving] = usePresence(
1149
+ pip && (pip.busy || unread) ? (pip.busy ? "busy" : "news") : null,
1150
+ 150,
1151
+ );
1152
+
1153
+ if (kept === null) {
1154
+ return null;
1155
+ }
1156
+
1157
+ return html`<button
1158
+ class=${`pip-bubble ${kept} ${leaving ? "leaving" : ""}`}
1159
+ aria-label=${kept === "busy" ? "PiP is working: open PiP" : "PiP has something new: open PiP"}
1160
+ title="PiP (Alt+A)"
1161
+ onClick=${() => openPip()}
1162
+ >
1163
+ <${Icon} name="pip" size=${22} />
1164
+ ${kept === "news" && html`<span class="pip-dot" aria-hidden="true"></span>`}
1165
+ </button>`;
1166
+ }
1167
+
1168
+ /** PiP's panel while it is open (kept a moment after, to animate out), or its mark while it is not. */
1169
+ export function PipHost() {
1170
+ const open = store.state.pipOpen && pipAvailable();
1171
+ const [kept, leaving] = usePresence(open || null, 180);
1172
+ // What a drag on the sheet dims as it goes: the scrim, not the app behind it.
1173
+ const scrim = useRef(null);
1174
+
1175
+ // Back closes it, as it closes a sheet.
1176
+ useBack(Boolean(open), closePip);
1177
+
1178
+ if (!pipAvailable()) {
1179
+ return null;
1180
+ }
1181
+
1182
+ if (!kept) {
1183
+ return html`<${PipBubble} />`;
1184
+ }
1185
+
1186
+ // On phones a scrim dims what is behind the sheet, and a tap on it closes it; wide screens have none.
1187
+ return html`<div
1188
+ class=${`pip-scrim ${leaving ? "leaving" : ""}`}
1189
+ ref=${scrim}
1190
+ aria-hidden="true"
1191
+ onClick=${closePip}
1192
+ ></div>
1193
+ <${PipPanel} leaving=${leaving} scrim=${scrim} />`;
1194
+ }
1195
+
1196
+ /** PiP in the rail: the way to it that is always there, marked while it works or has something new. */
1197
+ export function PipRailButton() {
1198
+ if (!pipAvailable()) {
1199
+ return null;
1200
+ }
1201
+
1202
+ const { pip, pipOpen } = store.state;
1203
+ const unread = pipUnread();
1204
+
1205
+ return html`<button
1206
+ class=${`rail-button rail-pip ${pip?.busy ? "lit" : ""} ${pipOpen ? "open" : ""}`}
1207
+ data-part="rail-button"
1208
+ data-state=${railState(pipOpen, Boolean(pip?.busy))}
1209
+ title="PiP, your assistant (Alt+A)"
1210
+ aria-label=${["PiP", pip?.busy && "working", unread && "something new"].filter(Boolean).join(", ")}
1211
+ aria-pressed=${pipOpen}
1212
+ onClick=${togglePip}
1213
+ >
1214
+ <${Icon} name="pip" size=${18} />
1215
+ ${unread && html`<span class="rail-news" aria-hidden="true"></span>`}
1216
+ </button>`;
1217
+ }