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,2695 @@
1
+ // The sidebar: the rail (Pi, the tools, and you; folded, numbered sessions too) and the session list beside it, in the
2
+ // sidebar, the drawer, and a phone's home screen; and the order and archiving of sessions.
3
+ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
4
+ import { Avatar, folderColor, initials } from "./avatar.js";
5
+ import { goHome, useBack } from "./back.js";
6
+ import {
7
+ ExtensionRailButtons,
8
+ sessionActions,
9
+ sessionChips,
10
+ sessionFilters,
11
+ sessionFilterTest,
12
+ sessionWords,
13
+ } from "./extension-ui.js";
14
+ import { useDragToClose } from "./gestures.js";
15
+ import { PeeksRailButton, wholeOnTile } from "./peeks.js";
16
+ import { PipRailButton } from "./pip.js";
17
+ import { sessionForest, unfolded } from "./session-tree.js";
18
+ import {
19
+ actions,
20
+ attempt,
21
+ canSteer,
22
+ chatReadStored,
23
+ collab,
24
+ navigate,
25
+ notify,
26
+ isUnread,
27
+ openSheet,
28
+ scoped,
29
+ sessionUnread,
30
+ setChatReadAt,
31
+ setUnread,
32
+ stillMoving,
33
+ store,
34
+ workspaceOrder,
35
+ foldsNow,
36
+ toggleFoldedLinked,
37
+ } from "./store.js";
38
+ import { dismiss as dismissSubagent } from "./subagents.js";
39
+ import { finishedUnseen, fromServer, markSeen, restoreSeen, seenSnapshot } from "./seen.js";
40
+ import { isPinned, prefs, setPrefs, togglePin } from "./theme.js";
41
+ import {
42
+ APPLE,
43
+ drawnFor,
44
+ formatWhen,
45
+ html,
46
+ Icon,
47
+ memo,
48
+ NO_HOVER,
49
+ railState,
50
+ scrimPress,
51
+ shortPath,
52
+ Slide,
53
+ timeAgo,
54
+ useMinute,
55
+ usePresence,
56
+ useScrollMore,
57
+ useSide,
58
+ useSlide,
59
+ } from "./ui.js";
60
+
61
+ /**
62
+ * Back to the session list, where it is not beside the conversation: back past the sessions opened from it, as a
63
+ * phone's back would go, or to it in this session's place when history does not lead there.
64
+ */
65
+ export const toSessions = () => goHome(() => navigate(null, { replace: true }));
66
+
67
+ /** The session list on its way: rows shaped like sessions, lit in turn. */
68
+ function LoadingSessions() {
69
+ return html`<div role="status" aria-label="Loading sessions">
70
+ ${[72, 54, 64, 46, 58].map(
71
+ (width, index) =>
72
+ html`<div
73
+ class="session-placeholder"
74
+ aria-hidden="true"
75
+ style=${`--width: ${width}%; --delay: ${index * 0.12}s`}
76
+ >
77
+ <span></span>
78
+ </div>`,
79
+ )}
80
+ </div>`;
81
+ }
82
+
83
+ const truncate = (text, length) => (text.length > length ? `${text.slice(0, length - 1)}…` : text);
84
+
85
+ const undoWord = () => (matchMedia("(pointer: coarse)").matches ? "Tap" : "Click");
86
+
87
+ /**
88
+ * Archive sessions, or bring them back, then say so in a notice that undoes it. Archiving the open session leaves it
89
+ * for the home screen; undoing that opens it again.
90
+ */
91
+ export async function setArchived(ids, archived, { undo = true } = {}) {
92
+ if (ids.length === 0) {
93
+ return;
94
+ }
95
+
96
+ const titles = new Map(
97
+ store.state.sessions.map((session) => [session.id, session.title ?? "New session"]),
98
+ );
99
+
100
+ markMoving(ids, archived);
101
+ const results = await Promise.allSettled(
102
+ ids.map((id) => actions.updateSession(id, { archived })),
103
+ );
104
+ const done = ids.filter((_, index) => results[index].status === "fulfilled");
105
+
106
+ // Rows that failed come back at once; the rest stay dimmed until the server's list shows them moved.
107
+ unmarkMoving(
108
+ ids.filter((id) => !done.includes(id)),
109
+ archived,
110
+ );
111
+ const failed = results.find((result) => result.status === "rejected");
112
+
113
+ if (failed) {
114
+ notify("error", failed.reason?.message ?? String(failed.reason));
115
+ }
116
+
117
+ const open = store.state.conversationId;
118
+ const left = undo && archived && done.includes(open);
119
+
120
+ if (left) {
121
+ navigate(null);
122
+ }
123
+
124
+ if (!undo || done.length === 0) {
125
+ return;
126
+ }
127
+
128
+ const what =
129
+ done.length === 1
130
+ ? `“${truncate(titles.get(done[0]) ?? "", 48)}”`
131
+ : `${done.length} sessions`;
132
+
133
+ notify(
134
+ "info",
135
+ `${archived ? "Archived" : "Unarchived"} ${what}. ${undoWord()} to undo.`,
136
+ async () => {
137
+ await setArchived(done, !archived, { undo: false });
138
+
139
+ if (left && store.state.conversationId === null) {
140
+ navigate(open);
141
+ }
142
+ },
143
+ );
144
+ }
145
+
146
+ /**
147
+ * Mark sessions as on their way into the archive (true) or out of it (false). The store drops a mark once the list
148
+ * shows the session where it was going; should that never happen (someone moved it straight back, or the request
149
+ * hangs), the mark goes after a while anyway.
150
+ */
151
+ function markMoving(ids, archived) {
152
+ store.set((state) => ({
153
+ moving: stillMoving(
154
+ { ...state.moving, ...Object.fromEntries(ids.map((id) => [id, archived])) },
155
+ state.sessions,
156
+ ),
157
+ }));
158
+ setTimeout(() => unmarkMoving(ids, archived), 10_000);
159
+ }
160
+
161
+ /** Drop the marks, but not ones made since the other way (an undo, say). */
162
+ function unmarkMoving(ids, archived) {
163
+ if (!ids.some((id) => store.state.moving[id] === archived)) {
164
+ return;
165
+ }
166
+
167
+ store.set((state) => {
168
+ const moving = { ...state.moving };
169
+
170
+ for (const id of ids) {
171
+ if (moving[id] === archived) {
172
+ delete moving[id];
173
+ }
174
+ }
175
+
176
+ return { moving };
177
+ });
178
+ }
179
+
180
+ const CLOSED_KEY = "pocket.closedGroups";
181
+
182
+ const readClosed = () => {
183
+ try {
184
+ return new Set(JSON.parse(localStorage.getItem(CLOSED_KEY) ?? "[]"));
185
+ } catch {
186
+ return new Set();
187
+ }
188
+ };
189
+
190
+ /** The fold's name for a screen reader: how many, and what its dot says (`aria-expanded` says whether they show). */
191
+ function foldLabel(kids, trouble) {
192
+ const count = `${kids} linked ${kids === 1 ? "session" : "sessions"}`;
193
+
194
+ return trouble === "waiting"
195
+ ? `${count}, one needs you`
196
+ : trouble === "failed"
197
+ ? `${count}, one failed`
198
+ : count;
199
+ }
200
+
201
+ /** Whether a session folded away under `id` waits for you or failed: the fold shows it, as a folded group does. */
202
+ function hiddenTrouble(group, id) {
203
+ const at = group.hidden.findIndex((row) => row.session.id === id);
204
+
205
+ if (at === -1) {
206
+ return undefined;
207
+ }
208
+
209
+ const depth = group.hidden[at].branches.length;
210
+
211
+ for (const row of group.hidden.slice(at + 1)) {
212
+ if (row.branches.length <= depth) {
213
+ break;
214
+ }
215
+
216
+ const shape = sessionMark(row.session).shape;
217
+
218
+ if (shape === "waiting" || shape === "failed") {
219
+ return shape;
220
+ }
221
+ }
222
+
223
+ return undefined;
224
+ }
225
+
226
+ const DAY = 86_400_000;
227
+
228
+ /** When today began, in this device's time zone: worked out once for each grouping, not once for each session. */
229
+ function todayStart() {
230
+ const today = new Date();
231
+
232
+ today.setHours(0, 0, 0, 0);
233
+
234
+ return today.getTime();
235
+ }
236
+
237
+ /** Which day bucket a time falls in, in this device's time zone: `start` is when today began (`todayStart`). */
238
+ function dayGroup(ms, start) {
239
+ if (ms >= start) {
240
+ return "Today";
241
+ }
242
+
243
+ if (ms >= start - DAY) {
244
+ return "Yesterday";
245
+ }
246
+
247
+ if (ms >= start - 6 * DAY) {
248
+ return "This week";
249
+ }
250
+
251
+ if (ms >= start - 29 * DAY) {
252
+ return "This month";
253
+ }
254
+
255
+ return "Earlier";
256
+ }
257
+
258
+ /** `~/Development/pi-pocket` with its last part bold, for a folder group's name. */
259
+ function FolderName({ path }) {
260
+ const at = path.lastIndexOf("/");
261
+
262
+ if (at <= 0) {
263
+ return html`<b class="last">${path}</b>`;
264
+ }
265
+
266
+ // A long path gives way before its last part does.
267
+ return html`<span class="first">${path.slice(0, at + 1)}</span>
268
+ <b class="last">${path.slice(at + 1)}</b>`;
269
+ }
270
+
271
+ /** The text with what matched the search marked. */
272
+ function Highlight({ text, needle }) {
273
+ if (!needle) {
274
+ return text;
275
+ }
276
+
277
+ const at = text.toLowerCase().indexOf(needle);
278
+
279
+ if (at === -1) {
280
+ return text;
281
+ }
282
+
283
+ return html`${text.slice(0, at)}
284
+ <mark>${text.slice(at, at + needle.length)}</mark>
285
+ ${text.slice(at + needle.length)}`;
286
+ }
287
+
288
+ /** Failed subagents nobody has dealt with (seen or dismissed), of a session's counts or the rail's totals. */
289
+ const failing = (counts) => (counts.failed ?? 0) - (counts.dealt ?? 0);
290
+
291
+ const failedRun = (session, state = store.state) =>
292
+ session.failed === true && (isUnread(session.id) || finishedUnseen(session, state));
293
+
294
+ function needOf(session, state = store.state) {
295
+ if (session.waiting) {
296
+ return "ask";
297
+ }
298
+
299
+ if (failedRun(session, state)) {
300
+ return "failed";
301
+ }
302
+
303
+ return failing(session.subagents ?? {}) > 0 ? "agents" : null;
304
+ }
305
+
306
+ function needsYouCount(sessions = store.state.sessions, state = store.state) {
307
+ return sessions.reduce(
308
+ (sum, session) => sum + (!session.archived && needOf(session, state) ? 1 : 0),
309
+ 0,
310
+ );
311
+ }
312
+
313
+ function slotOf(session, { state, collabs, answered }) {
314
+ const need = needOf(session, state);
315
+ const ask = session.approval;
316
+ // A call answered from here is no longer yours while the list has not heard yet, unless more wait behind it.
317
+ const answeredNow =
318
+ need === "ask" && ask !== undefined && answered.has(ask.id) && ask.count <= 1;
319
+
320
+ if (need !== null && !answeredNow) {
321
+ return "needs";
322
+ }
323
+
324
+ if (
325
+ isUnread(session.id) ||
326
+ finishedUnseen(session, state) ||
327
+ (collabs && session.id !== state.conversationId && sessionUnread(session, state))
328
+ ) {
329
+ return "ready";
330
+ }
331
+
332
+ const counts = session.subagents ?? {};
333
+
334
+ return session.busy ||
335
+ session.limited !== undefined ||
336
+ (counts.working ?? 0) + (counts.waiting ?? 0) > 0 ||
337
+ session.background > 0
338
+ ? "working"
339
+ : "quiet";
340
+ }
341
+
342
+ const NEED_RANK = { ask: 0, failed: 1, agents: 2 };
343
+
344
+ function priorityGroups(shown, ctx, held) {
345
+ const slots = { needs: [], ready: [], working: [], quiet: [] };
346
+
347
+ for (const session of shown) {
348
+ let slot = slotOf(session, ctx);
349
+
350
+ // Reading the open session moves it nowhere until another opens; a new need still comes first.
351
+ if (
352
+ session.id === held.id &&
353
+ held.slot !== null &&
354
+ slot !== held.slot &&
355
+ slot !== "needs" &&
356
+ !(held.slot === "needs" && held.asked)
357
+ ) {
358
+ slot = held.slot;
359
+ }
360
+
361
+ slots[slot].push(session);
362
+ }
363
+
364
+ const rank = (session) => NEED_RANK[needOf(session, ctx.state)] ?? 3;
365
+
366
+ slots.needs.sort((a, b) => {
367
+ const kinds = rank(a) - rank(b);
368
+
369
+ if (kinds !== 0) {
370
+ return kinds;
371
+ }
372
+
373
+ return rank(a) === 0
374
+ ? (a.approval?.at ?? 0) - (b.approval?.at ?? 0)
375
+ : (b.endedAt ?? b.updatedAt) - (a.endedAt ?? a.updatedAt);
376
+ });
377
+ const rowsOf = (list) => list.map((session) => ({ session, branches: [], descendants: 0 }));
378
+ const groups = [];
379
+
380
+ for (const [slot, label] of [
381
+ ["needs", "Needs you"],
382
+ ["ready", "Ready to read"],
383
+ ["working", "Working"],
384
+ ["quiet", "Quiet"],
385
+ ]) {
386
+ if (slots[slot].length > 0) {
387
+ const rows = rowsOf(slots[slot]);
388
+
389
+ groups.push({
390
+ key: `priority:${slot}`,
391
+ slot,
392
+ label,
393
+ total: rows.length,
394
+ rows,
395
+ hidden: rows,
396
+ });
397
+ }
398
+ }
399
+
400
+ return {
401
+ groups,
402
+ slots: new Map(
403
+ groups.flatMap((group) => group.rows.map((row) => [row.session.id, group.slot])),
404
+ ),
405
+ };
406
+ }
407
+
408
+ /** Groups that start folded: the person's first unfolding is kept as `!key` in the same stored set as the folds. */
409
+ const FOLDED_AT_FIRST = new Set(["priority:quiet"]);
410
+
411
+ /** How long the focus waits for the next call's Review to draw after an answer, before the list takes it. */
412
+ const FOCUS_WAIT_MS = 1000;
413
+
414
+ /** A flood of calls would push everything else away. */
415
+ const NEEDS_SHOWN = 6;
416
+
417
+ function visibleRows(group, asking, all) {
418
+ return group.slot !== "needs" || all || group.rows.length <= NEEDS_SHOWN
419
+ ? group.rows
420
+ : group.rows.filter((row, index) => index < NEEDS_SHOWN || row.session.id === asking);
421
+ }
422
+
423
+ async function dismissFailures(list) {
424
+ const runs = list.filter((session) => failedRun(session));
425
+ const ids = runs.map((session) => session.id);
426
+ const seen = seenSnapshot(ids);
427
+ const marked = ids.filter((id) => isUnread(id));
428
+ const agents = canSteer() ? list.flatMap((session) => session.failedAgents ?? []) : [];
429
+
430
+ markSeen(...ids);
431
+
432
+ const set = seenSnapshot(ids);
433
+
434
+ for (const id of marked) {
435
+ setUnread(id, false);
436
+ }
437
+
438
+ const results = await Promise.allSettled(
439
+ agents.map((agent) =>
440
+ dismissSubagent({ conversationId: agent.conversationId, answeredAt: agent.at }),
441
+ ),
442
+ );
443
+ const refused = results.find((result) => result.status === "rejected");
444
+
445
+ if (refused) {
446
+ notify("error", refused.reason?.message ?? String(refused.reason));
447
+ }
448
+
449
+ const what =
450
+ list.length === 1
451
+ ? `“${truncate(list[0].title ?? "New session", 48)}”`
452
+ : `${list.length} failed`;
453
+
454
+ // A subagent's failure that was dealt with stays dealt with: there is no way back, so no undo.
455
+ if (agents.length > 0 || ids.length === 0) {
456
+ notify("info", `Dismissed ${what}.`);
457
+
458
+ return;
459
+ }
460
+
461
+ notify("info", `Dismissed ${what}. ${undoWord()} to undo.`, () => {
462
+ const back = restoreSeen(seen, set);
463
+
464
+ for (const id of marked.filter((each) => back.has(each))) {
465
+ setUnread(id, true);
466
+ }
467
+ });
468
+ }
469
+
470
+ function markRead(list, { say = true } = {}) {
471
+ const ids = list.map((session) => session.id);
472
+ const seen = seenSnapshot(ids);
473
+ const marked = ids.filter((id) => isUnread(id));
474
+ const chats = list
475
+ .filter((session) => session.chatAt !== undefined && sessionUnread(session))
476
+ .map((session) => [session.id, store.state.chatReads[session.id] ?? 0, session.chatAt]);
477
+
478
+ markSeen(...ids);
479
+
480
+ const set = seenSnapshot(ids);
481
+
482
+ for (const id of marked) {
483
+ setUnread(id, false);
484
+ }
485
+
486
+ for (const [id, , read] of chats) {
487
+ setChatReadAt(id, read);
488
+ }
489
+
490
+ if (!say) {
491
+ return;
492
+ }
493
+
494
+ // Undo puts back only what is still as this made it: a session read since, here or in another tab, stays read.
495
+ notify("info", `Marked ${list.length} read. ${undoWord()} to undo.`, () => {
496
+ const back = restoreSeen(seen, set);
497
+
498
+ for (const id of marked.filter((each) => back.has(each) && !isUnread(each))) {
499
+ setUnread(id, true);
500
+ }
501
+
502
+ for (const [id, before, read] of chats) {
503
+ if (chatReadStored(id) === read) {
504
+ setChatReadAt(id, before);
505
+ }
506
+ }
507
+ });
508
+ }
509
+
510
+ /** "2 working · 1 failed subagents": a session's subagents, for the ⑂ mark's tooltip. */
511
+ function subagentsTip(counts) {
512
+ const shown = { ...counts, failed: failing(counts) };
513
+ const kinds = ["working", "waiting", "failed"].filter((kind) => shown[kind] > 0);
514
+ const total = kinds.reduce((sum, kind) => sum + shown[kind], 0);
515
+
516
+ return `${kinds.map((kind) => `${shown[kind]} ${kind}`).join(" · ")} subagent${total === 1 ? "" : "s"}`;
517
+ }
518
+
519
+ /**
520
+ * How long a finger rests on a row before its actions open; how far it may stray meanwhile (as far as a scroll, or the
521
+ * drawer's drag); and how long before the row shows the press, so a scroll's start does not light it.
522
+ */
523
+ const PRESS_MS = 450;
524
+ const PRESS_SLOP = 8;
525
+ const PRESS_SHOWS_MS = 100;
526
+
527
+ let pressedIn = null;
528
+
529
+ /**
530
+ * Select a session in the list where its row was held, and let taps there select more (or let go), as Ctrl/⌘+click
531
+ * does with a mouse. From the sheet a long press opens.
532
+ */
533
+ export function selectFromList(id) {
534
+ pressedIn?.current?.select(id);
535
+ }
536
+
537
+ export function selectedInList() {
538
+ return pressedIn?.current?.count() ?? 0;
539
+ }
540
+
541
+ export function deselectInList() {
542
+ pressedIn?.current?.clear();
543
+ }
544
+
545
+ /**
546
+ * The square at the start of a session's row: its folder's color, in the shape of where the session is. The first that
547
+ * holds wins: a call waiting for you, a request waiting for its provider's limit to clear, Pi or its subagents at work, a failed run (solid while new, drawn once seen),
548
+ * finished since this browser last looked or marked unread (solid), and read or never run (hollow).
549
+ */
550
+ function stateMark(session, working, marked, unseen = finishedUnseen(session)) {
551
+ const fresh = marked || unseen;
552
+
553
+ if (session.waiting) {
554
+ return { shape: "waiting", label: "Waiting for approval" };
555
+ }
556
+
557
+ // Pi's request waits for the provider's limit to clear: working, held up, until a time or a try.
558
+ if (session.limited !== undefined) {
559
+ return { shape: "limited", label: "Waiting for a usage limit" };
560
+ }
561
+
562
+ if (session.busy || working) {
563
+ return { shape: "working", label: "Working" };
564
+ }
565
+
566
+ if (session.failed) {
567
+ return fresh
568
+ ? { shape: "failed", label: "Failed, not read" }
569
+ : { shape: "failed seen", label: "Failed" };
570
+ }
571
+
572
+ return fresh ? { shape: "fresh", label: "Not read" } : { shape: "seen", label: "" };
573
+ }
574
+
575
+ /** A row's state for themes (`data-state`), by its square's shape: a documented name that stays when the squares change. */
576
+ const ROW_STATES = {
577
+ waiting: "waiting",
578
+ limited: "limited",
579
+ working: "working",
580
+ failed: "failed",
581
+ fresh: "done",
582
+ seen: "idle",
583
+ };
584
+
585
+ /**
586
+ * Sessions whose rows this page has drawn. A row rises in only the first time: back to the list on a phone builds the
587
+ * list anew, and every row rising in again made it flicker. A session new to the page (started since) still rises in.
588
+ */
589
+ const shownRows = new Set();
590
+
591
+ /** A session's square, as its row in the list draws it (the home screen's Jump back in too). */
592
+ export function sessionMark(session) {
593
+ const counts = session.subagents ?? {};
594
+
595
+ return stateMark(
596
+ session,
597
+ (counts.working ?? 0) + (counts.waiting ?? 0) > 0,
598
+ isUnread(session.id),
599
+ );
600
+ }
601
+
602
+ /**
603
+ * One session on one line: its folder's color in the shape of its state, its title, and on the right what goes on there (its working subagents,
604
+ * who else is in it, Pi working, a call waiting for you), unread chat, and how long ago. Its folder and model are in
605
+ * its tooltip. Memoized (`memo`): it reads nothing of the store as it draws, only its props, which `AllSessions` works
606
+ * out for it. `minute` and `extensionsRev` draw it again as time passes and as extensions' chips and words change.
607
+ */
608
+ function SessionRow({
609
+ session,
610
+ branches,
611
+ kids,
612
+ folded,
613
+ foldHeld,
614
+ foldTrouble,
615
+ onFold,
616
+ index,
617
+ number,
618
+ needle,
619
+ selected,
620
+ pressing,
621
+ folders,
622
+ onPick,
623
+ onSelect,
624
+ onMenu,
625
+ hoverAction,
626
+ open,
627
+ pinned,
628
+ marked,
629
+ unread,
630
+ unseen,
631
+ moving,
632
+ home,
633
+ meId,
634
+ collabs,
635
+ steers,
636
+ hovers,
637
+ slot,
638
+ need,
639
+ expanded,
640
+ answering,
641
+ glow,
642
+ ownCall,
643
+ onReview,
644
+ onAnswer,
645
+ onDismiss,
646
+ onRead,
647
+ }) {
648
+ // Where it rises in, in turn, when it is new to this page; null when it shows as it was.
649
+ const [arrival] = useState(() => (shownRows.has(session.id) ? null : index));
650
+
651
+ useLayoutEffect(() => {
652
+ shownRows.add(session.id);
653
+ }, []);
654
+ const title = session.title ?? "New session";
655
+ const path = shortPath(session.cwd, home);
656
+ const where = [
657
+ session.worktree ? `${path} ⎇ ${session.worktree.branch}` : path,
658
+ session.model,
659
+ ].filter(Boolean);
660
+ // A search can match the folder or model instead of the title: the row shows which.
661
+ let hit =
662
+ needle && !title.toLowerCase().includes(needle)
663
+ ? [path, session.cwd, session.model].find((text) =>
664
+ text?.toLowerCase().includes(needle),
665
+ )
666
+ : undefined;
667
+
668
+ // A path from the folder that matched: its start is the same in every row, and would push the match out of sight.
669
+ if (hit && hit !== session.model) {
670
+ const parts = hit.split("/");
671
+ const at = parts.findLastIndex((part) => part.toLowerCase().includes(needle));
672
+
673
+ hit = at > 0 ? `…/${parts.slice(at).join("/")}` : hit;
674
+ }
675
+
676
+ // Or a word an extension gave it, such as a tag.
677
+ if (needle && hit === undefined && !title.toLowerCase().includes(needle)) {
678
+ hit = sessionWords(session).find((word) => word.includes(needle));
679
+ }
680
+
681
+ // What extensions show on the row, under its title.
682
+ const chips = sessionChips(session);
683
+
684
+ const counts = session.subagents ?? {};
685
+ const live = (counts.working ?? 0) + (counts.waiting ?? 0);
686
+ const failed = failing(counts);
687
+ // Subagents at work, or failed ones nobody dealt with, but not over a call waiting for you: that says more.
688
+ const fork = !session.waiting && (live > 0 || failed > 0);
689
+ const person = collabs ? (session.people ?? []).find((each) => each.id !== meId) : undefined;
690
+ const mark = stateMark(session, live > 0, marked, unseen);
691
+ const ask = need === "ask" ? session.approval : undefined;
692
+ const names = (session.failedAgents ?? []).map((agent) => agent.name);
693
+ const why =
694
+ need === "ask"
695
+ ? ask && `${ask.tool} · ${ask.subject}`
696
+ : need === "failed"
697
+ ? `Run failed${session.failure ? `: ${session.failure}` : ""}`
698
+ : need === "agents"
699
+ ? failed === 1 && names.length > 0
700
+ ? `Subagent ${names[0]} failed`
701
+ : `${failed} subagents failed`
702
+ : undefined;
703
+ // A failed subagent is dealt with by someone who steers; a failed run is only seen, which anyone can do.
704
+ const dismisses =
705
+ need === "failed" ||
706
+ (need === "agents" && steers && (session.failedAgents ?? []).length > 0);
707
+ const limit =
708
+ slot === "working" && session.limited !== undefined
709
+ ? formatWhen(fromServer(session.limited))
710
+ : undefined;
711
+ const tip = [title, ...(why ? [why] : []), ...(folders ? where.reverse() : where)].join(" · ");
712
+ // Archive, pin, and mark-unread show on hover; an archived session only comes back, and only for people who steer.
713
+ const acts = !hovers
714
+ ? 0
715
+ : slot === "needs"
716
+ ? 0
717
+ : slot === "ready"
718
+ ? (steers ? 1 : 0) + 1 + (hoverAction ? 1 : 0)
719
+ : (steers ? 1 : 0) + (session.archived ? 0 : 2) + (hoverAction ? 1 : 0);
720
+
721
+ return html`<div
722
+ class=${`session-row ${kids > 0 ? "with-fold" : ""} ${arrival === null ? "" : "arriving"} ${slot === "needs" ? "needs-you" : ""} ${expanded ? "asking" : ""} ${glow ? "glow" : ""} ${open ? "active" : ""} ${selected ? "selected" : ""} ${pressing ? "pressing" : ""} ${moving ? "moving" : ""} ${marked ? "marked-unread" : ""} ${unseen ? "unseen" : ""} ${chips.length > 0 ? "with-chips" : ""} ${["no-acts", "one-act", "", "three-acts", "four-acts"][acts]}`}
723
+ data-part="session-row"
724
+ data-state=${ROW_STATES[mark.shape.split(" ")[0]]}
725
+ data-id=${session.id}
726
+ style=${`${arrival === null ? "" : `--i:${arrival};`}--linked-depth:${Math.min(branches.length, 3)}`}
727
+ >
728
+ ${
729
+ branches.length > 0 &&
730
+ html`<span class="session-branches" data-part="session-branches" aria-hidden="true">
731
+ ${branches.slice(-3).map(
732
+ (continues, index, visible) => html`<span
733
+ class=${`${continues ? "continues" : ""} ${index === visible.length - 1 ? "elbow" : ""}`}
734
+ ></span>`,
735
+ )}
736
+ </span>`
737
+ }
738
+ <button
739
+ class=${`session ${unread ? "unread" : ""}`}
740
+ data-part="session-button"
741
+ aria-current=${open ? "page" : undefined}
742
+ onPointerDown=${(event) => onSelect(event, session.id)}
743
+ onClick=${(event) => onPick(event, session.id)}
744
+ onContextMenu=${(event) => onMenu(event, session.id)}
745
+ title=${tip}
746
+ >
747
+ <span class="session-mark">
748
+ ${
749
+ selected
750
+ ? html`<span class="state-check" role="img" aria-label="Selected">
751
+ <${Icon} name="check" size=${9} />
752
+ </span>`
753
+ : html`<span
754
+ class=${`state-mark ${mark.shape}`}
755
+ data-part="session-mark"
756
+ style=${`--folder:${folderColor(session.cwd)}`}
757
+ role=${mark.label ? "img" : undefined}
758
+ aria-label=${mark.label || undefined}
759
+ aria-hidden=${mark.label ? undefined : "true"}
760
+ ></span>`
761
+ }
762
+ </span>
763
+ <span class=${`session-title ${hit ? "with-hit" : ""}`}>
764
+ ${
765
+ hit
766
+ ? html`<span class="session-name">${title}</span>
767
+ <span class="session-hit">
768
+ <${Highlight} text=${hit} needle=${needle} />
769
+ </span>`
770
+ : html`<${Highlight} text=${title} needle=${needle} />`
771
+ }
772
+ </span>
773
+ <span class="session-side">
774
+ ${
775
+ fork &&
776
+ html`<span
777
+ class=${`session-fork ${live > 0 ? "" : "failed"}`}
778
+ title=${subagentsTip(counts)}
779
+ >
780
+ <${Icon} name="fork" size=${10} />${live > 0 ? live : failed}
781
+ </span>`
782
+ }
783
+ ${
784
+ session.background > 0 &&
785
+ html`<span
786
+ class="session-background"
787
+ title=${`${session.background} ${session.background === 1 ? "command runs" : "commands run"} in the background`}
788
+ >
789
+ <${Icon} name="terminal" size=${10} />${session.background}
790
+ </span>`
791
+ }
792
+ ${
793
+ slot !== "needs" &&
794
+ !fork &&
795
+ person &&
796
+ html`<${Avatar} person=${person} size=${18} />`
797
+ }
798
+ ${
799
+ slot !== "needs" &&
800
+ session.busy &&
801
+ !session.waiting &&
802
+ session.limited === undefined &&
803
+ !fork &&
804
+ html`<span class="session-working" title="Working"></span>`
805
+ }
806
+ ${
807
+ slot === undefined &&
808
+ session.waiting &&
809
+ html`<span class="session-needs" title="Waiting for approval">
810
+ ${steers ? "needs you" : "waiting"}
811
+ </span>`
812
+ }
813
+ ${
814
+ slot !== "needs" &&
815
+ (unread || marked) &&
816
+ html`<span
817
+ class="unread-dot"
818
+ title=${marked ? "Marked unread" : "New chat messages"}
819
+ ></span>`
820
+ }
821
+ ${
822
+ limit &&
823
+ html`<span
824
+ class="session-limit"
825
+ data-part="session-limit"
826
+ title=${`Waiting for a usage limit to clear, at ${limit}`}
827
+ >
828
+ <${Icon} name="clock" size=${10} />${limit}
829
+ </span>`
830
+ }
831
+ ${
832
+ slot !== "needs" &&
833
+ !limit &&
834
+ html`<span class="session-time">${timeAgo(session.updatedAt)}</span>`
835
+ }
836
+ ${
837
+ number !== undefined &&
838
+ number < 9 &&
839
+ html`<kbd class="session-num">${number + 1}</kbd>`
840
+ }
841
+ </span>
842
+ </button>
843
+ ${
844
+ kids > 0 &&
845
+ html`<button
846
+ class=${`session-fold ${folded ? "folded" : ""}`}
847
+ data-part="session-fold"
848
+ aria-expanded=${!folded}
849
+ aria-label=${foldLabel(kids, foldTrouble)}
850
+ title=${
851
+ foldHeld
852
+ ? "The open session is among them, so they show"
853
+ : `${folded ? "Show" : "Hide"} ${kids} linked ${kids === 1 ? "session" : "sessions"}`
854
+ }
855
+ disabled=${foldHeld}
856
+ onClick=${() => onFold(session.id)}
857
+ >
858
+ ${
859
+ foldTrouble &&
860
+ html`<span class=${`group-trouble ${foldTrouble}`} aria-hidden="true"></span>`
861
+ }
862
+ <span class="session-fold-pill">
863
+ ${kids}
864
+ <${Icon} name="down" size=${10} />
865
+ </span>
866
+ </button>`
867
+ }
868
+ ${
869
+ chips.length > 0 &&
870
+ html`<span class="session-chips" data-part="session-chips">
871
+ ${chips.map((chip) =>
872
+ chip.run
873
+ ? html`<button
874
+ key=${chip.key}
875
+ class="session-chip"
876
+ data-part="session-chip"
877
+ title=${chip.title}
878
+ onClick=${chip.run}
879
+ >
880
+ ${chip.label}
881
+ </button>`
882
+ : html`<span
883
+ key=${chip.key}
884
+ class="session-chip"
885
+ data-part="session-chip"
886
+ title=${chip.title}
887
+ >
888
+ ${chip.label}
889
+ </span>`,
890
+ )}
891
+ </span>`
892
+ }
893
+ ${
894
+ need === "ask" &&
895
+ ask &&
896
+ html`<span class="session-quick" data-part="session-quick">
897
+ <button
898
+ class="quick-pill attn"
899
+ data-part="session-review"
900
+ data-review=${session.id}
901
+ aria-expanded=${expanded}
902
+ title="See the call, then allow or deny it"
903
+ onClick=${() => onReview(session.id)}
904
+ >
905
+ Review
906
+ </button>
907
+ </span>`
908
+ }
909
+ ${
910
+ need !== null &&
911
+ need !== "ask" &&
912
+ dismisses &&
913
+ html`<span class="session-quick" data-part="session-quick">
914
+ <button
915
+ class="quick-pill icon-only"
916
+ data-part="session-dismiss"
917
+ title=${`Dismiss: ${why}`}
918
+ aria-label=${`Dismiss: ${why}`}
919
+ onClick=${() => onDismiss(session.id)}
920
+ >
921
+ <${Icon} name="close" size=${12} />
922
+ </button>
923
+ </span>`
924
+ }
925
+ ${
926
+ hovers &&
927
+ slot !== "needs" &&
928
+ html`<span class="session-actions">
929
+ ${
930
+ hoverAction &&
931
+ html`<button
932
+ class="session-act session-ext-act"
933
+ title=${hoverAction.title}
934
+ aria-label=${hoverAction.title}
935
+ onClick=${() => hoverAction.run([session.id])}
936
+ >
937
+ <${Icon} path=${hoverAction.iconPath} size=${14} />
938
+ </button>`
939
+ }
940
+ ${
941
+ steers &&
942
+ html`<button
943
+ class="session-act"
944
+ title=${session.archived ? "Unarchive" : "Archive"}
945
+ aria-label=${session.archived ? "Unarchive" : "Archive"}
946
+ onClick=${() => setArchived([session.id], !session.archived)}
947
+ >
948
+ <${Icon} name=${session.archived ? "unarchive" : "archive"} size=${14} />
949
+ </button>`
950
+ }
951
+ ${
952
+ slot === "ready" &&
953
+ html`<button
954
+ class="session-act"
955
+ data-part="session-read"
956
+ title="Mark read"
957
+ aria-label="Mark read"
958
+ onClick=${() => onRead(session.id)}
959
+ >
960
+ <${Icon} name="check" size=${14} />
961
+ </button>`
962
+ }
963
+ ${
964
+ slot !== "ready" &&
965
+ !session.archived &&
966
+ html`<button
967
+ class=${`session-act session-pin ${pinned ? "on" : ""}`}
968
+ title=${pinned ? "Unpin" : "Pin to the top"}
969
+ aria-label=${pinned ? "Unpin" : "Pin"}
970
+ onClick=${() => togglePin(session.id)}
971
+ >
972
+ <${Icon} name="pin" size=${14} />
973
+ </button>`
974
+ }
975
+ ${
976
+ slot !== "ready" &&
977
+ !session.archived &&
978
+ html`<button
979
+ class=${`session-act session-unread ${marked ? "on" : ""}`}
980
+ title=${marked ? "Mark read" : "Mark unread"}
981
+ aria-label=${marked ? "Mark read" : "Mark unread"}
982
+ onClick=${() => setUnread(session.id, !marked)}
983
+ >
984
+ <${Icon} name=${marked ? "check" : "unread"} size=${14} />
985
+ </button>`
986
+ }
987
+ </span>`
988
+ }
989
+ ${
990
+ expanded &&
991
+ ask &&
992
+ html`<${NeedAsk}
993
+ session=${session}
994
+ ask=${ask}
995
+ steers=${steers}
996
+ ownCall=${ownCall}
997
+ answering=${answering}
998
+ onAnswer=${onAnswer}
999
+ />`
1000
+ }
1001
+ </div>`;
1002
+ }
1003
+
1004
+ /**
1005
+ * A command that does not show whole is not allowed from here, and a question from an extension (a form)
1006
+ * is declined or opened.
1007
+ */
1008
+ function NeedAsk({ session, ask, steers, ownCall, answering, onAnswer }) {
1009
+ const whole = wholeOnTile(ask);
1010
+ const ago = timeAgo(fromServer(ask.at));
1011
+ const more = ask.count > 1 ? ` · +${ask.count - 1}` : "";
1012
+ const tooLong =
1013
+ ask.form || whole ? "" : `${ask.reason ? " · " : ""}too long to allow from here`;
1014
+
1015
+ return html`<div class="need-ask" data-part="session-ask">
1016
+ <div
1017
+ class=${`need-command ${whole ? "" : "long"}`}
1018
+ data-part="session-ask-command"
1019
+ title=${ask.subject}
1020
+ >
1021
+ <code>
1022
+ <span class="need-tool"><${Icon} name="shield" size=${11} />${ask.tool}</span>
1023
+ ${ask.subject}
1024
+ </code>
1025
+ </div>
1026
+ <div class="need-why" data-part="session-ask-reason">${ask.reason}${tooLong}</div>
1027
+ <div class="need-foot">
1028
+ <span
1029
+ class="need-when"
1030
+ title=${ask.count > 1 ? `${ask.count - 1} more waiting in this session` : undefined}
1031
+ >${ago === "now" ? "just now" : `${ago} ago`}${more}</span>
1032
+ ${
1033
+ steers &&
1034
+ !ask.form &&
1035
+ html`<button
1036
+ class="need-button"
1037
+ data-part="session-deny"
1038
+ disabled=${answering}
1039
+ onClick=${() => onAnswer(session.id, ask.id, false)}
1040
+ >
1041
+ Deny
1042
+ </button>`
1043
+ }
1044
+ ${
1045
+ steers &&
1046
+ ask.form &&
1047
+ html`<button
1048
+ class="need-button"
1049
+ data-part="session-decline"
1050
+ title="Decline it from here; answer it where it waits"
1051
+ disabled=${answering}
1052
+ onClick=${() => onAnswer(session.id, ask.id, false)}
1053
+ >
1054
+ Decline
1055
+ </button>`
1056
+ }
1057
+ ${
1058
+ steers && !ask.form && whole && !ownCall
1059
+ ? html`<button
1060
+ class="need-button primary"
1061
+ data-part="session-allow"
1062
+ disabled=${answering}
1063
+ onClick=${() => onAnswer(session.id, ask.id, true)}
1064
+ >
1065
+ Allow
1066
+ </button>`
1067
+ : html`<button
1068
+ class=${`need-button ${steers && !ask.form ? "" : "primary"}`}
1069
+ data-part="session-ask-open"
1070
+ title="See the whole call where it waits"
1071
+ onClick=${() => navigate(ask.conversationId)}
1072
+ >
1073
+ Open
1074
+ </button>`
1075
+ }
1076
+ </div>
1077
+ </div>`;
1078
+ }
1079
+
1080
+ /** A row draws again when what it shows changes. Its place (`index`) counts only as it mounts, for its rise-in. */
1081
+ const MemoRow = memo(SessionRow, ["index"]);
1082
+
1083
+ /**
1084
+ * The branch lines a linked row draws, one array for each shape: the forest makes new ones each time, and a memoized
1085
+ * row would draw again for an array that only looks the same. There are few shapes (a row is at most a few deep).
1086
+ */
1087
+ const branchShapes = new Map();
1088
+
1089
+ function sameBranches(branches) {
1090
+ const key = branches.join();
1091
+ let shape = branchShapes.get(key);
1092
+
1093
+ if (shape === undefined) {
1094
+ shape = Object.freeze([...branches]);
1095
+ branchShapes.set(key, shape);
1096
+ }
1097
+
1098
+ return shape;
1099
+ }
1100
+
1101
+ /**
1102
+ * Sessions in groups: pinned, then by day or by folder. While searching, one flat list of matches. `today` is when
1103
+ * today began, and changes the day groups as days pass.
1104
+ */
1105
+ function groupsOf(shown, { tab, needle, home, pinned, today }) {
1106
+ if (needle !== "" || tab === "archived") {
1107
+ return [{ key: "flat", label: needle ? "Matches" : "Archived", rows: shown }];
1108
+ }
1109
+
1110
+ const groups = [];
1111
+ const pins = new Set(pinned);
1112
+ const byId = new Map(shown.map((session) => [session.id, session]));
1113
+ const first = pinned.map((id) => byId.get(id)).filter(Boolean);
1114
+
1115
+ if (first.length > 0) {
1116
+ groups.push({ key: "pinned", label: "Pinned", rows: first });
1117
+ }
1118
+
1119
+ const rest = shown.filter((session) => !pins.has(session.id));
1120
+ const byKey = new Map();
1121
+
1122
+ for (const session of rest) {
1123
+ const day = tab === "folders" ? "" : dayGroup(session.updatedAt, today);
1124
+ const key = tab === "folders" ? `dir:${session.cwd}` : `day:${day}`;
1125
+
1126
+ if (!byKey.has(key)) {
1127
+ byKey.set(key, {
1128
+ key,
1129
+ label:
1130
+ tab === "folders"
1131
+ ? html`<${FolderName} path=${shortPath(session.cwd, home)} />`
1132
+ : day,
1133
+ rows: [],
1134
+ });
1135
+ }
1136
+
1137
+ byKey.get(key).rows.push(session);
1138
+ }
1139
+
1140
+ return [...groups, ...byKey.values()];
1141
+ }
1142
+
1143
+ const TABS = [
1144
+ ["priority", "Priority"],
1145
+ ["recent", "Recent"],
1146
+ ["folders", "Folders"],
1147
+ ["archived", "Archived"],
1148
+ ];
1149
+
1150
+ const tabOf = (group) =>
1151
+ group === "folder" ? "folders" : group === "priority" ? "priority" : "recent";
1152
+
1153
+ /**
1154
+ * What the full list searched for and how far it was scrolled, kept while the tab lives: on a phone the list goes when a
1155
+ * session opens, and back from the session shows it again as it was.
1156
+ */
1157
+ const listKept = { query: "", scroll: 0 };
1158
+
1159
+ function AllSessions({ compact = false }) {
1160
+ const { sessions, sessionsLoaded, server, pinned } = store.state;
1161
+ const canStart = canSteer() && !scoped();
1162
+ const [query, setQueryState] = useState(() => (compact ? "" : listKept.query));
1163
+ const [tab, setTabState] = useState(() => tabOf(prefs().group));
1164
+ const [closed, setClosed] = useState(readClosed);
1165
+ const [asking, setAsking] = useState(null);
1166
+ const [answered, setAnswered] = useState(() => new Set());
1167
+ const [moved, setMoved] = useState(null);
1168
+ const [focusReview, setFocusReview] = useState(null);
1169
+ const [allNeeds, setAllNeeds] = useState(false);
1170
+ const opened = useRef({ id: null, slot: null, asked: false });
1171
+ const slotsShown = useRef(new Map());
1172
+ const askOrder = useRef([]);
1173
+ // Linked sessions folded away (`store.js`), but never above the open session, which always shows.
1174
+ const { foldedLinked, conversationId: openId } = store.state;
1175
+ const folded = useMemo(() => foldsNow(), [foldedLinked, openId, sessions]);
1176
+ // The sessions above the open one: their folds stay open, so their fold buttons do nothing and are off.
1177
+ const holdsOpen = useMemo(() => {
1178
+ const byId = new Map(sessions.map((session) => [session.id, session]));
1179
+ const above = new Set();
1180
+
1181
+ for (
1182
+ let at = byId.get(openId)?.linkedFrom?.id;
1183
+ at !== undefined && !above.has(at);
1184
+ at = byId.get(at)?.linkedFrom?.id
1185
+ ) {
1186
+ above.add(at);
1187
+ }
1188
+
1189
+ return above;
1190
+ }, [openId, sessions]);
1191
+ const [selected, setSelectedState] = useState(() => new Set());
1192
+ // Taps select rows instead of opening them: a selection started from a long press's sheet, on a touch screen.
1193
+ const [tapSelects, setTapSelects] = useState(false);
1194
+ // The row a finger holds down, before its actions open.
1195
+ const [pressing, setPressing] = useState(null);
1196
+ // The selection as drags and clicks see it between renders; the row a Shift+click extends from; the row a Ctrl/⌘ press
1197
+ // already selected, whose click then does nothing; the rows in view, in order.
1198
+ const picked = useRef(selected);
1199
+ const anchor = useRef(null);
1200
+ const held = useRef(null);
1201
+ const visible = useRef([]);
1202
+ const list = useRef(null);
1203
+ const tabs = useRef(null);
1204
+ const needle = query.trim().toLowerCase();
1205
+ const archived = tab === "archived";
1206
+
1207
+ const setQuery = (next) => {
1208
+ if (!compact) {
1209
+ listKept.query = next;
1210
+ }
1211
+
1212
+ setQueryState(next);
1213
+ };
1214
+
1215
+ // Scrolled back to where it was, once its rows are there.
1216
+ useLayoutEffect(() => {
1217
+ if (!compact && sessionsLoaded && list.current) {
1218
+ list.current.scrollTop = listKept.scroll;
1219
+ }
1220
+ }, [sessionsLoaded]);
1221
+
1222
+ const setSelected = (next) => {
1223
+ picked.current = next;
1224
+ setSelectedState(next);
1225
+
1226
+ if (next.size === 0) {
1227
+ setTapSelects(false);
1228
+ }
1229
+ };
1230
+
1231
+ // What Select in a held row's sheet does here; and what lets go of a press under way.
1232
+ const startSelect = useRef(null);
1233
+ const unpress = useRef(null);
1234
+
1235
+ startSelect.current = {
1236
+ select: (id) => {
1237
+ anchor.current = id;
1238
+ setSelected(new Set([...picked.current, id]));
1239
+ setTapSelects(true);
1240
+ },
1241
+ clear: () => clearSelection(),
1242
+ count: () => picked.current.size,
1243
+ };
1244
+
1245
+ useEffect(
1246
+ () => () => {
1247
+ unpress.current?.();
1248
+
1249
+ if (pressedIn === startSelect) {
1250
+ pressedIn = null;
1251
+ }
1252
+ },
1253
+ [],
1254
+ );
1255
+
1256
+ const clearSelection = () => {
1257
+ anchor.current = null;
1258
+ setSelected(new Set());
1259
+ };
1260
+
1261
+ const setTab = (next) => {
1262
+ setTabState(next);
1263
+ clearSelection();
1264
+
1265
+ if (next !== "archived") {
1266
+ setPrefs({
1267
+ group: next === "folders" ? "folder" : next === "priority" ? "priority" : "recent",
1268
+ });
1269
+ }
1270
+ };
1271
+
1272
+ // What changes the list's rows: the sessions and pins, the tab and the search, extensions' filters and words
1273
+ // (`extensionsRev`), and the day, which moves sessions between the day groups. Worked out again only when one of
1274
+ // them changes, not on every draw.
1275
+ const { extensionsRev, unread, peekSeen, chatReads, chatRead } = store.state;
1276
+ const minute = useMinute();
1277
+ const today = useMemo(todayStart, [minute]);
1278
+ const home = server?.home;
1279
+ const { shown, kept, groups } = useMemo(() => {
1280
+ // Extensions' filters that are on (`pocket.sessionFilter`): a session shows only when each keeps it.
1281
+ const kept = sessionFilterTest();
1282
+ const shown = sessions.filter(
1283
+ (session) =>
1284
+ Boolean(session.archived) === archived &&
1285
+ (needle === "" ||
1286
+ `${session.title ?? ""} ${session.cwd} ${shortPath(session.cwd, home)} ${session.model ?? ""} ${sessionWords(session).join(" ")}`
1287
+ .toLowerCase()
1288
+ .includes(needle)) &&
1289
+ (kept === null || kept(session)),
1290
+ );
1291
+
1292
+ if (tab === "priority" && needle === "") {
1293
+ const openId = store.state.conversationId;
1294
+
1295
+ if (opened.current.id !== openId) {
1296
+ opened.current = {
1297
+ id: openId,
1298
+ slot: slotsShown.current.get(openId) ?? null,
1299
+ asked: false,
1300
+ };
1301
+ }
1302
+
1303
+ if (shown.some((session) => session.id === openId && session.waiting)) {
1304
+ opened.current.asked = true;
1305
+ }
1306
+
1307
+ const { groups, slots } = priorityGroups(
1308
+ shown,
1309
+ { state: store.state, collabs: collab(), answered },
1310
+ opened.current,
1311
+ );
1312
+
1313
+ slotsShown.current = slots;
1314
+ askOrder.current = groups
1315
+ .filter((group) => group.slot === "needs")
1316
+ .flatMap((group) => group.rows.map((row) => row.session))
1317
+ .filter((session) => session.waiting && session.approval)
1318
+ .map((session) => session.id);
1319
+
1320
+ return { shown, kept, groups };
1321
+ }
1322
+
1323
+ const forest = sessionForest(shown, { pinned, folders: tab === "folders" });
1324
+ const groups = groupsOf(forest.roots, { tab, needle, home, pinned, today }).map((group) => {
1325
+ const rows = group.rows.flatMap((root) => forest.rows.get(root.id));
1326
+
1327
+ return {
1328
+ ...group,
1329
+ total: rows.length,
1330
+ rows: needle === "" ? unfolded(rows, folded) : rows,
1331
+ // What each folded row hides, for the marks it stands in for.
1332
+ hidden: needle === "" ? rows : [],
1333
+ };
1334
+ });
1335
+
1336
+ return { shown, kept, groups };
1337
+ }, [
1338
+ sessions,
1339
+ pinned,
1340
+ tab,
1341
+ needle,
1342
+ home,
1343
+ today,
1344
+ extensionsRev,
1345
+ folded,
1346
+ unread,
1347
+ peekSeen,
1348
+ chatReads,
1349
+ chatRead,
1350
+ store.state.conversationId,
1351
+ store.state.server,
1352
+ answered,
1353
+ ]);
1354
+
1355
+ // Folded groups: a group's key is in `closed`; Quiet starts folded, and `!key` there says it was opened.
1356
+ const isClosed = (key) =>
1357
+ key !== "flat" && (closed.has(key) || (FOLDED_AT_FIRST.has(key) && !closed.has(`!${key}`)));
1358
+
1359
+ visible.current = useMemo(
1360
+ () =>
1361
+ groups.flatMap((group) =>
1362
+ isClosed(group.key)
1363
+ ? []
1364
+ : visibleRows(group, asking, allNeeds).map(({ session }) => session.id),
1365
+ ),
1366
+ [groups, closed, asking, allNeeds],
1367
+ );
1368
+ const chosen = useMemo(() => {
1369
+ if (selected.size === 0) {
1370
+ return [];
1371
+ }
1372
+
1373
+ // A row a fold hides is not chosen: an action runs only on rows the person can see were picked.
1374
+ const rows = new Set(
1375
+ groups.flatMap((group) => group.rows.map(({ session }) => session.id)),
1376
+ );
1377
+
1378
+ return shown
1379
+ .filter((session) => selected.has(session.id) && rows.has(session.id))
1380
+ .map((session) => session.id);
1381
+ }, [shown, groups, selected]);
1382
+ // Taps select while the bar shows: not for rows selected and then hidden (archived, searched away, or folded).
1383
+ const tapping = tapSelects && chosen.length > 0;
1384
+ const order = workspaceOrder();
1385
+ const numbers = useMemo(
1386
+ () => new Map(order.map((session, index) => [session.id, index])),
1387
+ [order],
1388
+ );
1389
+
1390
+ /** The rows from `from` to `to` as they show, or just `to` when either is out of view. */
1391
+ const span = (from, to) => {
1392
+ const ids = visible.current;
1393
+ const a = ids.indexOf(from);
1394
+ const b = ids.indexOf(to);
1395
+
1396
+ return a === -1 || b === -1 ? [to] : ids.slice(Math.min(a, b), Math.max(a, b) + 1);
1397
+ };
1398
+
1399
+ /**
1400
+ * A plain click opens the session. Shift+click selects from the last row picked (or the open one) to this row;
1401
+ * Ctrl/⌘+Enter on a focused row selects it or lets it go.
1402
+ */
1403
+ const pick = (event, id) => {
1404
+ // The press already selected, even if Ctrl/⌘ was let go before the button.
1405
+ if (held.current === id && event.detail > 0) {
1406
+ held.current = null;
1407
+
1408
+ return;
1409
+ }
1410
+
1411
+ if (event.shiftKey) {
1412
+ // From the last row picked, or else the open session, if it shows; or else from this row on.
1413
+ if (!visible.current.includes(anchor.current)) {
1414
+ const open = store.state.conversationId;
1415
+
1416
+ anchor.current = visible.current.includes(open) ? open : id;
1417
+ }
1418
+
1419
+ setSelected(new Set([...picked.current, ...span(anchor.current, id)]));
1420
+
1421
+ return;
1422
+ }
1423
+
1424
+ if (event.ctrlKey || event.metaKey || tapping) {
1425
+ const next = new Set(picked.current);
1426
+
1427
+ if (next.has(id)) {
1428
+ next.delete(id);
1429
+ } else {
1430
+ next.add(id);
1431
+ }
1432
+
1433
+ anchor.current = id;
1434
+ setSelected(next);
1435
+
1436
+ return;
1437
+ }
1438
+
1439
+ clearSelection();
1440
+ navigate(id);
1441
+ };
1442
+
1443
+ /**
1444
+ * A finger (or a pen) held on a row opens its actions in a sheet, as hovering shows them to a mouse: touch screens
1445
+ * have no hover. The row shows the press while it is held; moving (a scroll, a drag) lets it go. The click the lift
1446
+ * may then make, on the row or on the scrim that rose under it, does nothing. While the finger is held nothing on
1447
+ * the page can be selected: the sheet rises under the finger, and Android's own long press would otherwise select
1448
+ * the word there and raise its Copy bar over the sheet.
1449
+ */
1450
+ const press = (event, id) => {
1451
+ const session = sessions.find((each) => each.id === id);
1452
+
1453
+ // Nothing to offer: an archived session, for someone who cannot bring it back.
1454
+ if (!event.isPrimary || !session || (session.archived && !canSteer())) {
1455
+ return;
1456
+ }
1457
+
1458
+ const { pointerId, clientX: x, clientY: y } = event;
1459
+ let fired = false;
1460
+ let after = 0;
1461
+ const root = document.documentElement;
1462
+ const shows = setTimeout(() => setPressing(id), PRESS_SHOWS_MS);
1463
+
1464
+ const open = setTimeout(() => {
1465
+ // Gone meanwhile (someone deleted it): nothing to open.
1466
+ if (!store.state.sessions.some((each) => each.id === id)) {
1467
+ return stop();
1468
+ }
1469
+
1470
+ fired = true;
1471
+ setPressing(null);
1472
+ pressedIn = startSelect;
1473
+ // Over the drawer, which stays: Select goes on there.
1474
+ store.set({ sheet: { type: "session", id } });
1475
+ }, PRESS_MS);
1476
+
1477
+ const move = (each) => {
1478
+ if (
1479
+ each.pointerId === pointerId &&
1480
+ !fired &&
1481
+ Math.hypot(each.clientX - x, each.clientY - y) >= PRESS_SLOP
1482
+ ) {
1483
+ stop();
1484
+ }
1485
+ };
1486
+
1487
+ const lift = (each) => {
1488
+ if (each.pointerId !== pointerId) {
1489
+ return;
1490
+ }
1491
+
1492
+ if (!fired) {
1493
+ return stop();
1494
+ }
1495
+
1496
+ // The lift's click comes at once, if at all; the next press is someone else's tap.
1497
+ removeEventListener("pointerup", lift, true);
1498
+ removeEventListener("pointercancel", lift, true);
1499
+ addEventListener("pointerdown", stop, true);
1500
+ after = setTimeout(stop, 400);
1501
+ };
1502
+
1503
+ // A finger's mouse events only: its mousedown can close the scrim before the click, and Enter on a sheet's
1504
+ // item is a click too. Keep the guard through mousedown so the click cannot act on an item under the lift.
1505
+ const eat = (each) => {
1506
+ if (fired && each.detail > 0) {
1507
+ each.preventDefault();
1508
+ each.stopPropagation();
1509
+
1510
+ if (each.type === "click") {
1511
+ stop();
1512
+ }
1513
+ }
1514
+ };
1515
+
1516
+ // Android's own long press: no menu, and no text selection. The row's own text cannot be selected already,
1517
+ // but the sheet this press opens, rising under the finger, could be: Android would select the word under it
1518
+ // and raise its Copy bar over the sheet. So, while the finger is held, the page selects nothing.
1519
+ const quiet = (each) => each.preventDefault();
1520
+ const hold = (each) => each.preventDefault();
1521
+
1522
+ const stop = () => {
1523
+ unpress.current = null;
1524
+ clearTimeout(shows);
1525
+ clearTimeout(open);
1526
+ clearTimeout(after);
1527
+ setPressing((now) => (now === id ? null : now));
1528
+ root.classList.remove("holding");
1529
+ removeEventListener("pointermove", move, true);
1530
+ removeEventListener("pointerup", lift, true);
1531
+ removeEventListener("pointercancel", lift, true);
1532
+ removeEventListener("pointerdown", stop, true);
1533
+ removeEventListener("mousedown", eat, true);
1534
+ removeEventListener("click", eat, true);
1535
+ removeEventListener("contextmenu", quiet, true);
1536
+ removeEventListener("selectstart", hold, true);
1537
+ };
1538
+
1539
+ unpress.current?.();
1540
+ unpress.current = stop;
1541
+ root.classList.add("holding");
1542
+ addEventListener("pointermove", move, true);
1543
+ addEventListener("pointerup", lift, true);
1544
+ addEventListener("pointercancel", lift, true);
1545
+ addEventListener("mousedown", eat, true);
1546
+ addEventListener("click", eat, true);
1547
+ addEventListener("contextmenu", quiet, true);
1548
+ addEventListener("selectstart", hold, true);
1549
+ };
1550
+
1551
+ // Ctrl+click (a Mac's right-click) still selects; Shift+right-click keeps the browser's own menu.
1552
+ // A long press already did its own.
1553
+ const menu = (event, id) => {
1554
+ if (event.shiftKey || event.defaultPrevented) {
1555
+ return;
1556
+ }
1557
+
1558
+ event.preventDefault();
1559
+ const session = sessions.find((each) => each.id === id);
1560
+
1561
+ if (event.ctrlKey || !session || (session.archived && !canSteer())) {
1562
+ return;
1563
+ }
1564
+
1565
+ pressedIn = startSelect;
1566
+ store.set({ sheet: { type: "session", id, at: { x: event.clientX, y: event.clientY } } });
1567
+ };
1568
+
1569
+ /**
1570
+ * Ctrl/⌘+press on a row selects it (or, if it was selected, unselects it); dragging on does the same to every row
1571
+ * between it and the pointer. Once the pointer moves, the list scrolls along near its top or bottom edge. A finger
1572
+ * held on a row opens its actions instead.
1573
+ */
1574
+ const select = (event, id) => {
1575
+ held.current = null;
1576
+
1577
+ if (event.button !== 0) {
1578
+ return;
1579
+ }
1580
+
1581
+ if (event.pointerType !== "mouse") {
1582
+ press(event, id);
1583
+
1584
+ return;
1585
+ }
1586
+
1587
+ if (event.shiftKey) {
1588
+ // No text selection: the click extends the session selection instead.
1589
+ event.preventDefault();
1590
+
1591
+ return;
1592
+ }
1593
+
1594
+ if (!event.ctrlKey && !event.metaKey) {
1595
+ return;
1596
+ }
1597
+
1598
+ event.preventDefault();
1599
+ held.current = id;
1600
+ const box = list.current;
1601
+ const root = document.documentElement;
1602
+ const before = picked.current;
1603
+ const adding = !before.has(id);
1604
+
1605
+ anchor.current = id;
1606
+ let reached = null;
1607
+
1608
+ const reach = (to) => {
1609
+ if (to === reached) {
1610
+ return;
1611
+ }
1612
+
1613
+ reached = to;
1614
+ const next = new Set(before);
1615
+
1616
+ for (const each of span(id, to)) {
1617
+ if (adding) {
1618
+ next.add(each);
1619
+ } else {
1620
+ next.delete(each);
1621
+ }
1622
+ }
1623
+
1624
+ setSelected(next);
1625
+ };
1626
+
1627
+ reach(id);
1628
+ const start = event.clientY;
1629
+ let y = start;
1630
+
1631
+ // The row at the pointer's height, held inside the list so a drag past its sides or ends still counts.
1632
+ const under = () => {
1633
+ const rect = box.getBoundingClientRect();
1634
+ const row = document
1635
+ .elementFromPoint(
1636
+ rect.left + box.clientWidth / 2,
1637
+ Math.min(rect.bottom - 2, Math.max(rect.top + 2, y)),
1638
+ )
1639
+ ?.closest?.(".session-row[data-id]");
1640
+
1641
+ if (!row || !box.contains(row)) {
1642
+ return;
1643
+ }
1644
+
1645
+ const found = visible.current.find((each) => String(each) === row.dataset.id);
1646
+
1647
+ if (found !== undefined) {
1648
+ reach(found);
1649
+ }
1650
+ };
1651
+
1652
+ // No frame until the pointer moves: a press near an edge is not a drag.
1653
+ let frame = 0;
1654
+
1655
+ const scroll = () => {
1656
+ const rect = box.getBoundingClientRect();
1657
+ const edge = 36;
1658
+ const past =
1659
+ y < rect.top + edge
1660
+ ? y - rect.top - edge
1661
+ : y > rect.bottom - edge
1662
+ ? y - rect.bottom + edge
1663
+ : 0;
1664
+
1665
+ if (past !== 0) {
1666
+ box.scrollTop += Math.max(-24, Math.min(24, past / 2));
1667
+ under();
1668
+ }
1669
+
1670
+ frame = requestAnimationFrame(scroll);
1671
+ };
1672
+
1673
+ const move = (each) => {
1674
+ // The button came up where this page did not hear it, say in another window.
1675
+ if ((each.buttons & 1) === 0) {
1676
+ return stop();
1677
+ }
1678
+
1679
+ y = each.clientY;
1680
+
1681
+ if (frame === 0 && Math.abs(y - start) > 4) {
1682
+ frame = requestAnimationFrame(scroll);
1683
+ }
1684
+
1685
+ under();
1686
+ };
1687
+
1688
+ const stop = () => {
1689
+ cancelAnimationFrame(frame);
1690
+ root.classList.remove("selecting");
1691
+ removeEventListener("pointermove", move);
1692
+ removeEventListener("pointerup", stop);
1693
+ removeEventListener("pointercancel", stop);
1694
+ removeEventListener("blur", stop);
1695
+ };
1696
+
1697
+ root.classList.add("selecting");
1698
+ getSelection()?.removeAllRanges();
1699
+ addEventListener("pointermove", move);
1700
+ addEventListener("pointerup", stop);
1701
+ addEventListener("pointercancel", stop);
1702
+ addEventListener("blur", stop);
1703
+ };
1704
+
1705
+ const archiveChosen = () => {
1706
+ clearSelection();
1707
+ setArchived(chosen, !archived);
1708
+ };
1709
+
1710
+ const allPinned = chosen.length > 0 && chosen.every((id) => pinned.includes(id));
1711
+
1712
+ const pinChosen = () => {
1713
+ for (const id of chosen) {
1714
+ if (isPinned(id) === allPinned) {
1715
+ togglePin(id);
1716
+ }
1717
+ }
1718
+
1719
+ clearSelection();
1720
+ };
1721
+
1722
+ // Esc lets go of the selection, unless something else takes it: a sheet, the launcher, a text field, or a menu.
1723
+ const selecting = selected.size > 0;
1724
+
1725
+ // On a touch screen, so does back.
1726
+ useBack(tapping, clearSelection);
1727
+
1728
+ useEffect(() => {
1729
+ if (!selecting) {
1730
+ return;
1731
+ }
1732
+
1733
+ const onKey = (event) => {
1734
+ if (
1735
+ event.key !== "Escape" ||
1736
+ event.defaultPrevented ||
1737
+ store.state.sheet ||
1738
+ store.state.launcher
1739
+ ) {
1740
+ return;
1741
+ }
1742
+
1743
+ // Taken: this Esc lets go of the selection, and closes nothing else.
1744
+ event.preventDefault();
1745
+ clearSelection();
1746
+ };
1747
+
1748
+ addEventListener("keydown", onKey);
1749
+
1750
+ return () => removeEventListener("keydown", onKey);
1751
+ }, [selecting]);
1752
+
1753
+ const toggleFold = (id) => toggleFoldedLinked(id);
1754
+
1755
+ const review = (id) => setAsking((now) => (now === id ? null : id));
1756
+
1757
+ const answer = async (id, askId, allow) => {
1758
+ const ask = store.state.sessions.find((each) => each.id === id)?.approval;
1759
+
1760
+ // The row answers the call it showed, never another: one answered elsewhere meanwhile is not answered for it.
1761
+ if (ask?.id !== askId) {
1762
+ notify(
1763
+ "info",
1764
+ "That call was answered elsewhere. Look at the next one before you answer it.",
1765
+ );
1766
+
1767
+ return;
1768
+ }
1769
+
1770
+ if (answered.has(ask.id)) {
1771
+ return;
1772
+ }
1773
+
1774
+ const next = ask.count > 1 ? id : (askOrder.current.find((each) => each !== id) ?? null);
1775
+ const settle = (change) =>
1776
+ setAnswered((now) => {
1777
+ const copy = new Set(now);
1778
+
1779
+ change(copy);
1780
+
1781
+ return copy;
1782
+ });
1783
+
1784
+ settle((copy) => copy.add(ask.id));
1785
+
1786
+ if ((await attempt(() => actions.approve(ask.id, allow))) === undefined) {
1787
+ settle((copy) => copy.delete(ask.id));
1788
+
1789
+ return;
1790
+ }
1791
+
1792
+ notify("info", `${allow ? "Allowed" : "Denied"}: ${truncate(ask.subject, 60)}`);
1793
+ setMoved(id);
1794
+ setTimeout(() => setMoved((now) => (now === id ? null : now)), 2500);
1795
+ setAsking(next);
1796
+ setFocusReview(next ?? "list");
1797
+ };
1798
+
1799
+ useEffect(() => {
1800
+ if (focusReview === null) {
1801
+ return;
1802
+ }
1803
+
1804
+ const box = list.current;
1805
+ const target =
1806
+ focusReview === "list"
1807
+ ? box?.querySelector("button.session")
1808
+ : box?.querySelector(`[data-review="${focusReview}"]`);
1809
+
1810
+ if (target) {
1811
+ target.focus();
1812
+ setFocusReview(null);
1813
+
1814
+ return;
1815
+ }
1816
+
1817
+ // Not drawn yet (the list has not heard of the answer): each draw looks again, and later the list takes the focus,
1818
+ // so it never stays on a button that went away.
1819
+ const timer = setTimeout(() => {
1820
+ (box?.querySelector("button.session") ?? box)?.focus();
1821
+ setFocusReview(null);
1822
+ }, FOCUS_WAIT_MS);
1823
+
1824
+ return () => clearTimeout(timer);
1825
+ }, [focusReview, groups]);
1826
+
1827
+ useEffect(() => {
1828
+ const pending = new Set(sessions.map((session) => session.approval?.id).filter(Boolean));
1829
+
1830
+ setAnswered((now) =>
1831
+ [...now].every((id) => pending.has(id))
1832
+ ? now
1833
+ : new Set([...now].filter((id) => pending.has(id))),
1834
+ );
1835
+
1836
+ if (
1837
+ asking !== null &&
1838
+ !sessions.some((session) => session.id === asking && session.approval)
1839
+ ) {
1840
+ setAsking(null);
1841
+ }
1842
+ }, [sessions]);
1843
+
1844
+ const dismissOne = (id) => {
1845
+ const session = sessions.find((each) => each.id === id);
1846
+
1847
+ if (session) {
1848
+ dismissFailures([session]);
1849
+ }
1850
+ };
1851
+
1852
+ const dismissAll = (rows) => dismissFailures(rows.map((row) => row.session));
1853
+
1854
+ const readOne = (id) => {
1855
+ const session = sessions.find((each) => each.id === id);
1856
+
1857
+ if (session) {
1858
+ markRead([session], { say: false });
1859
+ }
1860
+ };
1861
+
1862
+ const toggleGroup = (key) => {
1863
+ const next = new Set(closed);
1864
+
1865
+ if (isClosed(key)) {
1866
+ next.delete(key);
1867
+ next.add(`!${key}`);
1868
+ } else {
1869
+ next.add(key);
1870
+ next.delete(`!${key}`);
1871
+ }
1872
+
1873
+ localStorage.setItem(CLOSED_KEY, JSON.stringify([...next]));
1874
+ setClosed(next);
1875
+ };
1876
+
1877
+ // Priority's tab changes width with its count, so the marker is measured again when the count changes.
1878
+ const needCount = useMemo(
1879
+ () => needsYouCount(sessions),
1880
+ [sessions, unread, peekSeen, store.state.server],
1881
+ );
1882
+ const tabBar = useSlide(tabs, "button.on", "x", `${tab}:${needCount}`);
1883
+ const count = useMemo(() => sessions.filter((session) => !session.archived).length, [sessions]);
1884
+ const filters = sessionFilters();
1885
+ const steers = canSteer();
1886
+ // Made again only when extensions or this person's steering change: rows keep the same action while they do not.
1887
+ const extActions = useMemo(sessionActions, [extensionsRev, steers]);
1888
+ const hoverAction = extActions.find((action) => action.iconPath !== null);
1889
+ // Rows' handlers that stay the same from draw to draw, so a row draws again only when what it shows changes. They
1890
+ // call this draw's `pick` and `select`, which see this draw's selection.
1891
+ const handlers = useRef(null);
1892
+
1893
+ handlers.current = { pick, select, menu, toggleFold, review, answer, dismissOne, readOne };
1894
+ const [onPick] = useState(() => (event, id) => handlers.current.pick(event, id));
1895
+ const [onSelect] = useState(() => (event, id) => handlers.current.select(event, id));
1896
+ const [onMenu] = useState(() => (event, id) => handlers.current.menu(event, id));
1897
+ const [onFold] = useState(() => (id) => handlers.current.toggleFold(id));
1898
+ const [onReview] = useState(() => (id) => handlers.current.review(id));
1899
+ const [onAnswer] = useState(
1900
+ () => (id, askId, allow) => handlers.current.answer(id, askId, allow),
1901
+ );
1902
+ const [onDismiss] = useState(() => (id) => handlers.current.dismissOne(id));
1903
+ const [onRead] = useState(() => (id) => handlers.current.readOne(id));
1904
+ // What every row reads of the store, read once here: rows read none of it themselves (`SessionRow`). Marks, seen
1905
+ // marks, and read times come through `isUnread`, `finishedUnseen`, and `sessionUnread`.
1906
+ const { conversationId, me, moving } = store.state;
1907
+ const collabs = collab();
1908
+ // Row buttons that only a hovering pointer shows (`NO_HOVER`): touch screens draw none.
1909
+ const hovers = !NO_HOVER.matches;
1910
+
1911
+ const rowOf = ({ session, branches, descendants }, index, group) => {
1912
+ const open = session.id === conversationId && !session.archived;
1913
+ // Linked sessions fold under the one that started them; a search shows them all, with nothing to fold.
1914
+ const kids = needle === "" ? descendants : 0;
1915
+ const isFolded = kids > 0 && folded.has(session.id);
1916
+
1917
+ return html`<${MemoRow}
1918
+ key=${session.id}
1919
+ session=${session}
1920
+ branches=${sameBranches(branches)}
1921
+ kids=${kids}
1922
+ folded=${isFolded}
1923
+ foldHeld=${holdsOpen.has(session.id)}
1924
+ foldTrouble=${isFolded ? hiddenTrouble(group, session.id) : undefined}
1925
+ onFold=${onFold}
1926
+ index=${index}
1927
+ number=${numbers.get(session.id)}
1928
+ needle=${needle}
1929
+ selected=${selected.has(session.id)}
1930
+ pressing=${pressing === session.id}
1931
+ folders=${tab === "folders" && needle === ""}
1932
+ onPick=${onPick}
1933
+ onSelect=${onSelect}
1934
+ onMenu=${onMenu}
1935
+ hoverAction=${hoverAction}
1936
+ open=${open}
1937
+ pinned=${isPinned(session.id)}
1938
+ marked=${isUnread(session.id)}
1939
+ unread=${collabs && !open && sessionUnread(session)}
1940
+ unseen=${finishedUnseen(session)}
1941
+ moving=${moving[session.id] !== undefined}
1942
+ home=${home}
1943
+ meId=${me?.id}
1944
+ collabs=${collabs}
1945
+ steers=${steers}
1946
+ hovers=${hovers}
1947
+ minute=${minute}
1948
+ extensionsRev=${extensionsRev}
1949
+ slot=${group.slot}
1950
+ need=${group.slot === "needs" ? needOf(session) : null}
1951
+ expanded=${asking === session.id && group.slot === "needs"}
1952
+ answering=${session.approval !== undefined && answered.has(session.approval.id)}
1953
+ glow=${moved === session.id && group.slot !== "needs"}
1954
+ ownCall=${
1955
+ session.approval !== undefined &&
1956
+ server?.approvalRule === "others" &&
1957
+ me?.role !== "owner" &&
1958
+ // Nobody known to have asked is not someone else: the server leaves that one to the owner.
1959
+ (session.approval.requestedBy === undefined ||
1960
+ session.approval.requestedBy === me?.id)
1961
+ }
1962
+ onReview=${onReview}
1963
+ onAnswer=${onAnswer}
1964
+ onDismiss=${onDismiss}
1965
+ onRead=${onRead}
1966
+ />`;
1967
+ };
1968
+
1969
+ let index = 0;
1970
+
1971
+ return html`<div
1972
+ class=${`sessions ${compact ? "compact" : ""} ${tapping ? "tap-selecting" : ""}`}
1973
+ data-part="session-list"
1974
+ >
1975
+ <div class="sessions-head">
1976
+ <span class="sessions-name" data-part="session-list-title">Sessions</span>
1977
+ <span class="sessions-count">${sessionsLoaded ? count : ""}</span>
1978
+ ${
1979
+ canStart &&
1980
+ html`<button
1981
+ class="new-button"
1982
+ title="New session (Alt+N)"
1983
+ onClick=${() => openSheet({ type: "cwd", mode: "new", fromList: true })}
1984
+ >
1985
+ <${Icon} name="plus" size=${14} />
1986
+ New
1987
+ </button>`
1988
+ }
1989
+ </div>
1990
+ <label class=${`search ${query ? "filled" : ""}`} data-part="session-search">
1991
+ <${Icon} name="search" size=${14} />
1992
+ <input
1993
+ placeholder="Search sessions"
1994
+ aria-label="Search sessions"
1995
+ value=${query}
1996
+ onInput=${(event) => setQuery(event.currentTarget.value)}
1997
+ onKeyDown=${(event) => {
1998
+ if (event.key !== "Escape" || query === "") {
1999
+ return;
2000
+ }
2001
+
2002
+ // Taken: this Esc clears the search, not the selection.
2003
+ event.preventDefault();
2004
+ setQuery("");
2005
+ }}
2006
+ />
2007
+ ${
2008
+ query
2009
+ ? html`<button
2010
+ class="search-clear"
2011
+ aria-label="Clear"
2012
+ onClick=${() => setQuery("")}
2013
+ >
2014
+ <${Icon} name="close" size=${13} />
2015
+ </button>`
2016
+ : html`<span
2017
+ class="search-keys"
2018
+ title="Launcher"
2019
+ aria-hidden="true"
2020
+ onClick=${(event) => {
2021
+ event.preventDefault();
2022
+ store.set({ launcher: true, drawer: false });
2023
+ }}
2024
+ >
2025
+ ${APPLE ? "⌘K" : "Ctrl K"}
2026
+ </span>
2027
+ <button
2028
+ class="search-launcher"
2029
+ title="Launcher"
2030
+ aria-label="Open the launcher"
2031
+ onClick=${(event) => {
2032
+ event.preventDefault();
2033
+ store.set({ launcher: true, drawer: false });
2034
+ }}
2035
+ >
2036
+ <${Icon} name="command" size=${14} />
2037
+ </button>`
2038
+ }
2039
+ ${filters.map(
2040
+ (filter) => html`<button
2041
+ key=${filter.key}
2042
+ class=${`search-filter badge-host ${filter.on ? "on" : ""}`}
2043
+ data-part="session-filter"
2044
+ data-state=${filter.on ? "on" : "off"}
2045
+ title=${filter.title}
2046
+ aria-label=${[filter.title, filter.badge, filter.on ? "on" : ""].filter(Boolean).join(", ")}
2047
+ onClick=${(event) => {
2048
+ event.preventDefault();
2049
+ filter.run();
2050
+ }}
2051
+ >
2052
+ <${Icon} path=${filter.iconPath} size=${14} />
2053
+ ${filter.badge !== "" && html`<span class="badge">${filter.badge}</span>`}
2054
+ </button>`,
2055
+ )}
2056
+ </label>
2057
+ <div class="session-tabs" data-part="session-tabs" role="tablist" ref=${tabs}>
2058
+ ${TABS.map(
2059
+ ([key, label]) => html`<button
2060
+ key=${key}
2061
+ role="tab"
2062
+ data-part="session-tab"
2063
+ data-tab=${key}
2064
+ aria-selected=${tab === key}
2065
+ aria-label=${
2066
+ key === "archived"
2067
+ ? "Archived"
2068
+ : key === "priority" && needCount > 0
2069
+ ? `Priority, ${needCount} ${needCount === 1 ? "needs" : "need"} you`
2070
+ : undefined
2071
+ }
2072
+ title=${key === "archived" ? "Archived" : undefined}
2073
+ class=${tab === key ? "on" : ""}
2074
+ onClick=${() => setTab(key)}
2075
+ >
2076
+ ${key === "archived" ? html`<${Icon} name="archive" size=${14} />` : label}
2077
+ ${
2078
+ key === "priority" &&
2079
+ needCount > 0 &&
2080
+ html`<span
2081
+ class="tab-count"
2082
+ data-part="session-tab-count"
2083
+ aria-hidden="true"
2084
+ >
2085
+ ${needCount}
2086
+ </span>`
2087
+ }
2088
+ </button>`,
2089
+ )}
2090
+ <${Slide} box=${tabBar} axis="x" />
2091
+ </div>
2092
+ <div
2093
+ class="session-items"
2094
+ ref=${list}
2095
+ tabindex="-1"
2096
+ onScroll=${(event) => !compact && (listKept.scroll = event.currentTarget.scrollTop)}
2097
+ >
2098
+ ${!sessionsLoaded && html`<${LoadingSessions} />`}
2099
+ ${
2100
+ sessionsLoaded &&
2101
+ shown.length === 0 &&
2102
+ html`<div class="sessions-empty">
2103
+ ${kept !== null && !needle ? "No sessions match the filters." : archived ? "No archived sessions." : needle ? "No matches." : "No sessions yet. Start one with New."}
2104
+ </div>`
2105
+ }
2106
+ ${
2107
+ sessionsLoaded &&
2108
+ tab === "priority" &&
2109
+ needle === "" &&
2110
+ shown.length > 0 &&
2111
+ !groups.some((group) => group.slot === "needs") &&
2112
+ html`<div class="priority-clear" data-part="session-clear">
2113
+ <${Icon} name="check" size=${13} />
2114
+ <span>Nothing needs you</span>
2115
+ </div>`
2116
+ }
2117
+ ${groups.map((group) => {
2118
+ const folded = isClosed(group.key);
2119
+ // Needs you does not fold: what waits there must show.
2120
+ const still = group.slot === "needs";
2121
+ const foldable = group.key !== "flat" && !still;
2122
+ const toggle = still ? undefined : () => foldable && toggleGroup(group.key);
2123
+ const rows = visibleRows(group, asking, allNeeds);
2124
+ const failedRows =
2125
+ group.slot === "needs"
2126
+ ? group.rows.filter((row) => {
2127
+ const need = needOf(row.session);
2128
+
2129
+ return (
2130
+ need === "failed" ||
2131
+ (need === "agents" &&
2132
+ steers &&
2133
+ (row.session.failedAgents ?? []).length > 0)
2134
+ );
2135
+ })
2136
+ : [];
2137
+ const action =
2138
+ group.slot === "needs" && failedRows.length > 1
2139
+ ? {
2140
+ label: `Dismiss ${failedRows.length} failed`,
2141
+ run: () => dismissAll(failedRows),
2142
+ }
2143
+ : group.slot === "ready"
2144
+ ? {
2145
+ label: "Mark all read",
2146
+ run: () => markRead(group.rows.map((row) => row.session)),
2147
+ }
2148
+ : undefined;
2149
+ // A folded group hides its rows' marks: say when one waits for you or its run failed.
2150
+ const trouble = folded
2151
+ ? group.hidden
2152
+ .map((row) => sessionMark(row.session).shape)
2153
+ .find((shape) => shape === "waiting" || shape === "failed")
2154
+ : undefined;
2155
+
2156
+ const head =
2157
+ group.key !== "flat" || needle
2158
+ ? html`<${still ? "div" : "button"}
2159
+ class=${`group-head ${group.slot === "needs" ? "attn" : ""}`}
2160
+ data-part="session-group-head"
2161
+ onClick=${toggle}
2162
+ aria-expanded=${still ? undefined : !folded}
2163
+ >
2164
+ <span class="group-name" data-part="session-group-name">
2165
+ ${
2166
+ typeof group.label === "string"
2167
+ ? html`<b>${group.label}</b>`
2168
+ : group.label
2169
+ }
2170
+ </span>
2171
+ ${
2172
+ trouble &&
2173
+ html`<span
2174
+ class=${`group-trouble ${trouble}`}
2175
+ role="img"
2176
+ aria-label=${trouble === "waiting" ? "A session needs you" : "A session failed"}
2177
+ title=${trouble === "waiting" ? "A session here needs you" : "A session here failed"}
2178
+ ></span>`
2179
+ }
2180
+ <span class="group-count" data-part="session-group-count">
2181
+ ${group.total}
2182
+ </span>
2183
+ ${foldable && html`<${Icon} name="down" size=${11} />`}
2184
+ <//>`
2185
+ : null;
2186
+
2187
+ return html`<section
2188
+ class=${`session-group ${folded ? "closed" : ""}`}
2189
+ data-part="session-group"
2190
+ data-group=${group.slot}
2191
+ key=${`${tab}:${group.key}`}
2192
+ >
2193
+ ${
2194
+ action
2195
+ ? html`<div class="group-bar" data-part="session-group-bar">
2196
+ ${head}
2197
+ <button
2198
+ class="group-action"
2199
+ data-part="session-group-action"
2200
+ onClick=${action.run}
2201
+ >
2202
+ ${action.label}
2203
+ </button>
2204
+ </div>`
2205
+ : head
2206
+ }
2207
+ <div class="group-body" inert=${folded}>
2208
+ <div>
2209
+ ${rows.map((row) => rowOf(row, index++, group))}
2210
+ ${
2211
+ rows.length < group.rows.length &&
2212
+ html`<button
2213
+ class="more-needs"
2214
+ data-part="session-more"
2215
+ onClick=${() => setAllNeeds(true)}
2216
+ >
2217
+ Show ${group.rows.length - rows.length} more
2218
+ </button>`
2219
+ }
2220
+ </div>
2221
+ </div>
2222
+ </section>`;
2223
+ })}
2224
+ </div>
2225
+ ${
2226
+ chosen.length > 0 &&
2227
+ html`<div class="select-bar" role="group" aria-label="Selected sessions">
2228
+ <span class="select-count">
2229
+ <b>${chosen.length}</b>
2230
+ <span class="select-word"> selected</span>
2231
+ </span>
2232
+ ${
2233
+ canSteer() &&
2234
+ html`<button class="button" onClick=${archiveChosen}>
2235
+ ${archived ? "Unarchive" : "Archive"}
2236
+ </button>`
2237
+ }
2238
+ ${
2239
+ !archived &&
2240
+ html`<button class="button" onClick=${pinChosen}>
2241
+ ${allPinned ? "Unpin" : "Pin"}
2242
+ </button>`
2243
+ }
2244
+ ${extActions.map(
2245
+ (action) => html`<button
2246
+ key=${action.key}
2247
+ class="button"
2248
+ title=${`${action.title} (${action.module})`}
2249
+ onClick=${() => {
2250
+ clearSelection();
2251
+ action.run(chosen);
2252
+ }}
2253
+ >
2254
+ ${action.label}
2255
+ </button>`,
2256
+ )}
2257
+ <button
2258
+ class="select-clear"
2259
+ title="Clear the selection (Esc)"
2260
+ aria-label="Clear the selection"
2261
+ onClick=${clearSelection}
2262
+ >
2263
+ <${Icon} name="close" size=${14} />
2264
+ </button>
2265
+ </div>`
2266
+ }
2267
+ </div>`;
2268
+ }
2269
+
2270
+ /**
2271
+ * The store's keys the session list reads as it draws, itself and through what it calls: `prefs()` (`appearance`),
2272
+ * `canSteer()`, `scoped()`, and `collab()` (`me`, `server`), `isPinned` and `workspaceOrder` (`pinned`), `isUnread`
2273
+ * (`unread`), `sessionUnread` (`conversationId`, `chatRead`, `chatReads`, `me`), `finishedUnseen` and `sessionMark`
2274
+ * (`peekSeen`, and `server` for when this browser started), and extensions' chips, words, filters, and actions
2275
+ * (`extensionsRev`). The sheet and the launcher it reads only as keys are pressed.
2276
+ */
2277
+ const LIST_KEYS = [
2278
+ "sessions",
2279
+ "sessionsLoaded",
2280
+ "server",
2281
+ "me",
2282
+ "pinned",
2283
+ "unread",
2284
+ "moving",
2285
+ "conversationId",
2286
+ "chatRead",
2287
+ "chatReads",
2288
+ "peekSeen",
2289
+ "appearance",
2290
+ "extensionsRev",
2291
+ "foldedLinked",
2292
+ ];
2293
+
2294
+ /**
2295
+ * Drawn again only when what it reads changes (`LIST_KEYS`): not as an answer streams, nor for the chat, people, or
2296
+ * the connection. Back to the list and each reconnect change little of it.
2297
+ */
2298
+ export const SessionList = drawnFor(LIST_KEYS, AllSessions);
2299
+
2300
+ /**
2301
+ * Subagents across the sessions, by state, as the rail counts them: archived sessions only while a subagent works
2302
+ * there, as the subagents board shows them.
2303
+ */
2304
+ export function subagentTotals(sessions = store.state.sessions) {
2305
+ const totals = { working: 0, waiting: 0, failed: 0, stopped: 0, done: 0, dealt: 0 };
2306
+
2307
+ for (const session of sessions) {
2308
+ const counts = session.subagents;
2309
+
2310
+ if (!counts || (session.archived && !counts.working && !counts.waiting)) {
2311
+ continue;
2312
+ }
2313
+
2314
+ for (const state of Object.keys(totals)) {
2315
+ totals[state] += counts[state] ?? 0;
2316
+ }
2317
+ }
2318
+
2319
+ return totals;
2320
+ }
2321
+
2322
+ /** Open the subagents board in the conversation's place, or close it. */
2323
+ export const toggleBoard = () =>
2324
+ store.set((state) =>
2325
+ state.board
2326
+ ? { board: false, boardAgents: null }
2327
+ : { board: true, drawer: false, page: null },
2328
+ );
2329
+
2330
+ /** The folded sidebar's sessions, numbered like Waybar's workspaces. */
2331
+ function RailTiles() {
2332
+ const { conversationId } = store.state;
2333
+ const items = useRef(null);
2334
+ const order = workspaceOrder();
2335
+ // The tiles are as tall as each other: the open session's place in the order says where its marker goes.
2336
+ const at = order.findIndex((session) => session.id === conversationId);
2337
+ const indicator = useSlide(items, ".ws.active", "y", at);
2338
+ const more = useScrollMore();
2339
+ // One ref for both: the marker's slide reads the element, and the fades follow its scrolling.
2340
+ const [ref] = useState(() => (element) => {
2341
+ items.current = element;
2342
+ more(element);
2343
+ });
2344
+
2345
+ return html`<div class="rail-items" ref=${ref} style=${`--tiles:${order.length}`}>
2346
+ <${Slide} box=${indicator} />
2347
+ ${order.map(
2348
+ (session, index) => html`<button
2349
+ key=${session.id}
2350
+ class=${`ws ${session.id === conversationId ? "active" : ""} ${session.busy ? "busy" : ""} ${session.waiting ? "waiting" : ""} ${session.background > 0 ? "has-background" : ""}`}
2351
+ style=${`--i:${index}`}
2352
+ title=${`${session.title ?? "New session"}${index < 9 ? ` (Alt+${index + 1})` : ""}`}
2353
+ aria-label=${`${session.title ?? "New session"}${session.waiting ? ", needs you" : session.busy ? ", working" : session.background > 0 ? ", running commands in the background" : ""}`}
2354
+ aria-current=${session.id === conversationId ? "page" : undefined}
2355
+ onClick=${() => navigate(session.id)}
2356
+ >
2357
+ ${index < 9 ? index + 1 : initials(session.title ?? "New session")}
2358
+ ${
2359
+ ((collab() && sessionUnread(session)) || isUnread(session.id)) &&
2360
+ session.id !== conversationId &&
2361
+ html`<span class="unread-dot"></span>`
2362
+ }
2363
+ </button>`,
2364
+ )}
2365
+ </div>`;
2366
+ }
2367
+
2368
+ /**
2369
+ * The rail beside the session list: Pi (home), the sessions (which fold the sidebar), then the tools (peek tiles, PiP,
2370
+ * running now, the subagents board, people, providers, the theme) and you. Folded, it holds the sessions too, numbered.
2371
+ * In the drawer and on a phone's home screen it does not fold, and Pi is a mark.
2372
+ */
2373
+ function Rail({ foldable = false, folded = false }) {
2374
+ const { sessions, board, me } = store.state;
2375
+ const canStart = canSteer() && !scoped();
2376
+ // Counted again only when the session list changes, not on each draw of the rail.
2377
+ const { busy, agents } = useMemo(
2378
+ () => ({
2379
+ // Commands Pi runs in the background are at work too, after its answer ended.
2380
+ busy: sessions.filter((session) => session.busy || session.background > 0).length,
2381
+ agents: subagentTotals(sessions),
2382
+ }),
2383
+ [sessions],
2384
+ );
2385
+ const live = agents.working + agents.waiting;
2386
+ const failed = failing(agents);
2387
+ const { unread, peekSeen, server } = store.state;
2388
+ const needs = useMemo(() => needsYouCount(sessions), [sessions, unread, peekSeen, server]);
2389
+ const sessionsLabel =
2390
+ needs > 0 ? `Sessions, ${needs} ${needs === 1 ? "needs" : "need"} you` : "Sessions";
2391
+ const needsBadge =
2392
+ needs > 0 && html`<span class="rail-count attn" data-part="rail-needs">${needs}</span>`;
2393
+ const keys = APPLE ? "⌘B" : "Ctrl+B";
2394
+ const fold = () => setPrefs({ sidebar: folded ? "open" : "rail" });
2395
+ const role = me?.role === "owner" ? "owner" : me?.role === "viewer" ? "view only" : "guest";
2396
+ // A rail with more buttons than room scrolls as a whole, and fades the edge where more is.
2397
+ const more = useScrollMore();
2398
+
2399
+ return html`<nav class="rail" data-part="rail" aria-label="Sessions and tools" ref=${more}>
2400
+ ${
2401
+ foldable
2402
+ ? html`<button
2403
+ class="rail-brand"
2404
+ data-part="brand-mark"
2405
+ title="Home"
2406
+ aria-label="Home"
2407
+ onClick=${toSessions}
2408
+ >
2409
+ π
2410
+ </button>`
2411
+ : html`<span class="rail-brand" data-part="brand-mark" aria-hidden="true">π</span>`
2412
+ }
2413
+ <span class="rail-gap"></span>
2414
+ ${
2415
+ foldable
2416
+ ? html`<button
2417
+ class=${`rail-button ${folded ? "" : "on"}`}
2418
+ data-part="rail-button"
2419
+ data-state=${railState(!folded)}
2420
+ title=${`Sessions (${keys} ${folded ? "unfolds" : "folds"} the list)`}
2421
+ aria-label=${sessionsLabel}
2422
+ aria-expanded=${!folded}
2423
+ onClick=${fold}
2424
+ >
2425
+ <${Icon} name="chat" size=${19} />
2426
+ ${needsBadge}
2427
+ </button>`
2428
+ : html`<span
2429
+ class="rail-button on"
2430
+ data-part="rail-button"
2431
+ data-state="open"
2432
+ title="Sessions"
2433
+ aria-current="page"
2434
+ >
2435
+ <${Icon} name="chat" size=${19} />
2436
+ ${needsBadge}
2437
+ </span>`
2438
+ }
2439
+ ${!folded && html`<span class="rail-fill"></span>`}
2440
+ ${
2441
+ folded &&
2442
+ canStart &&
2443
+ html`<button
2444
+ class="rail-button rail-new"
2445
+ data-part="rail-button"
2446
+ title="New session (Alt+N)"
2447
+ aria-label="New session"
2448
+ onClick=${() => openSheet({ type: "cwd", mode: "new" })}
2449
+ >
2450
+ <${Icon} name="plus" size=${19} />
2451
+ </button>`
2452
+ }
2453
+ ${folded && html`<${RailTiles} />`}
2454
+ ${foldable && html`<${PeeksRailButton} />`}
2455
+ <${PipRailButton} />
2456
+ <button
2457
+ class=${`rail-button rail-running ${busy > 0 ? "lit" : ""}`}
2458
+ data-part="rail-button"
2459
+ data-state=${railState(false, busy > 0)}
2460
+ title="Running now"
2461
+ aria-label=${busy > 0 ? `Running now, ${busy}` : "Running now"}
2462
+ onClick=${() => openSheet({ type: "running" })}
2463
+ >
2464
+ <${Icon} name="pulse" size=${19} />
2465
+ ${busy > 0 && html`<span class="rail-count">${busy}</span>`}
2466
+ </button>
2467
+ <button
2468
+ class=${`rail-button rail-agents ${live > 0 ? "lit" : ""} ${board ? "open" : ""}`}
2469
+ data-part="rail-button"
2470
+ data-state=${railState(board, live > 0)}
2471
+ title="Subagents in every session"
2472
+ aria-label=${[
2473
+ "Subagents",
2474
+ live > 0 && `${live} at work`,
2475
+ agents.waiting > 0 && `${agents.waiting} waiting for approval`,
2476
+ failed > 0 && `${failed} failed`,
2477
+ ]
2478
+ .filter(Boolean)
2479
+ .join(", ")}
2480
+ aria-pressed=${board}
2481
+ onClick=${toggleBoard}
2482
+ >
2483
+ <${Icon} name="fork" size=${19} />
2484
+ ${live > 0 && html`<span class="rail-count">${live}</span>`}
2485
+ ${
2486
+ (failed > 0 || agents.waiting > 0) &&
2487
+ html`<span class="rail-trouble" aria-hidden="true"></span>`
2488
+ }
2489
+ </button>
2490
+ <${ExtensionRailButtons} />
2491
+ ${
2492
+ collab()
2493
+ ? html`<button
2494
+ class="rail-button"
2495
+ data-part="rail-button"
2496
+ title=${canStart ? "People and invites" : "People"}
2497
+ aria-label="People"
2498
+ onClick=${() => openSheet({ type: "people" })}
2499
+ >
2500
+ <${Icon} name="users" size=${19} />
2501
+ </button>`
2502
+ : html`<button
2503
+ class="rail-button"
2504
+ data-part="rail-button"
2505
+ title="Sign in another device"
2506
+ aria-label="Devices"
2507
+ onClick=${() => openSheet({ type: "invite" })}
2508
+ >
2509
+ <${Icon} name="users" size=${19} />
2510
+ </button>`
2511
+ }
2512
+ ${
2513
+ me?.role === "owner" &&
2514
+ html`<button
2515
+ class="rail-button"
2516
+ data-part="rail-button"
2517
+ title="Model providers"
2518
+ aria-label="Providers"
2519
+ onClick=${() => openSheet({ type: "providers" })}
2520
+ >
2521
+ <${Icon} name="key" size=${19} />
2522
+ </button>`
2523
+ }
2524
+ <button
2525
+ class="rail-button"
2526
+ data-part="rail-button"
2527
+ title="Theme, tiling, motion"
2528
+ aria-label="Theme"
2529
+ onClick=${() => openSheet({ type: "appearance" })}
2530
+ >
2531
+ <${Icon} name="palette" size=${19} />
2532
+ </button>
2533
+ <button
2534
+ class="rail-button rail-me"
2535
+ data-part="rail-button"
2536
+ title=${`${me?.name ?? ""} · ${role}`}
2537
+ aria-label="Your name"
2538
+ onClick=${() => openSheet({ type: "name" })}
2539
+ >
2540
+ ${me && html`<${Avatar} person=${me} size=${30} />`}
2541
+ </button>
2542
+ </nav>`;
2543
+ }
2544
+
2545
+ /**
2546
+ * The store's keys the rail reads as it draws, itself and through its buttons: the session list's for its numbered
2547
+ * sessions (`RailTiles`), the board, PiP's (`pip`, `pipOpen`), peek tiles' (`appearance`), and extensions' buttons,
2548
+ * which show their page or panel as open (`page`, `extPanel`, `extensionsRev`).
2549
+ */
2550
+ const RAIL_KEYS = [
2551
+ "sessions",
2552
+ "server",
2553
+ "me",
2554
+ "pinned",
2555
+ "unread",
2556
+ "peekSeen",
2557
+ "conversationId",
2558
+ "chatRead",
2559
+ "chatReads",
2560
+ "appearance",
2561
+ "board",
2562
+ "pip",
2563
+ "pipOpen",
2564
+ "page",
2565
+ "extPanel",
2566
+ "extensionsRev",
2567
+ "foldedLinked",
2568
+ ];
2569
+
2570
+ /** Drawn again only when what it reads changes (`RAIL_KEYS`): not as an answer streams. */
2571
+ export const RailNav = drawnFor(RAIL_KEYS, Rail);
2572
+
2573
+ /** The sidebar's list is this wide at least and at most; the rail beside it stays 56px. */
2574
+ const LIST_MIN = 204;
2575
+ const LIST_MAX = 464;
2576
+
2577
+ /** The sidebar's usual width, the rail and its list together: the one a new browser starts with (theme.js). */
2578
+ export const SIDEBAR_WIDTH = 312;
2579
+
2580
+ /** Drag the sidebar's right edge to resize its list; a double click puts it back to its usual width. */
2581
+ export function ResizeHandle() {
2582
+ const ref = useRef(null);
2583
+ // A theme may put the sidebar on the right: the handle goes to its other edge, and drags the other way.
2584
+ const side = useSide(ref, (handle) => handle.parentElement);
2585
+
2586
+ const start = (event) => {
2587
+ if (event.button !== 0) {
2588
+ return;
2589
+ }
2590
+
2591
+ event.preventDefault();
2592
+ const root = document.documentElement;
2593
+ const sidebar = event.currentTarget.parentElement;
2594
+ const box = sidebar.getBoundingClientRect();
2595
+ // The rail and the borders, which keep their width.
2596
+ const rest = sidebar.offsetWidth - (sidebar.querySelector(".sessions")?.offsetWidth ?? 0);
2597
+ let width = prefs().sidebarWidth;
2598
+
2599
+ root.classList.add("resizing");
2600
+
2601
+ // No wider than the stylesheet lets it be: 40% of the screen.
2602
+ const max = Math.min(LIST_MAX + rest, Math.max(SIDEBAR_WIDTH, innerWidth * 0.4));
2603
+
2604
+ const move = (each) => {
2605
+ const across = side === "right" ? box.right - each.clientX : each.clientX - box.left;
2606
+
2607
+ width = Math.round(Math.min(max, Math.max(LIST_MIN + rest, across)));
2608
+ root.style.setProperty("--sidebar-w", `${width}px`);
2609
+ };
2610
+
2611
+ const stop = () => {
2612
+ root.classList.remove("resizing");
2613
+ removeEventListener("pointermove", move);
2614
+ removeEventListener("pointerup", stop);
2615
+ removeEventListener("pointercancel", stop);
2616
+ setPrefs({ sidebarWidth: width });
2617
+ };
2618
+
2619
+ addEventListener("pointermove", move);
2620
+ addEventListener("pointerup", stop);
2621
+ addEventListener("pointercancel", stop);
2622
+ };
2623
+
2624
+ return html`<div
2625
+ class=${`resize-handle ${side === "right" ? "at-left" : ""}`}
2626
+ ref=${ref}
2627
+ role="separator"
2628
+ aria-orientation="vertical"
2629
+ title="Drag to resize"
2630
+ onPointerDown=${start}
2631
+ onDblClick=${() => setPrefs({ sidebarWidth: SIDEBAR_WIDTH })}
2632
+ ></div>`;
2633
+ }
2634
+
2635
+ /** The rail and the session list, sliding in from the left on narrow screens. */
2636
+ export function Drawer() {
2637
+ const [open, leaving] = usePresence(store.state.drawer || null, 200);
2638
+ const ref = useRef(null);
2639
+ const close = () => store.set({ drawer: false });
2640
+ // A theme may slide it in from the right: it is dragged back that way.
2641
+ const side = useSide(ref);
2642
+
2643
+ useBack(store.state.drawer === true, close);
2644
+ // Not under a row's actions, which a long press opens over it: the finger that opened them may still move.
2645
+ useDragToClose(ref, {
2646
+ dir: side,
2647
+ onClose: close,
2648
+ enabled: Boolean(open) && !leaving && !store.state.sheet,
2649
+ });
2650
+ // Esc closes it, as it does a sheet; one over it closes first.
2651
+ useEffect(() => {
2652
+ if (!open || leaving) {
2653
+ return undefined;
2654
+ }
2655
+
2656
+ const onKey = (event) => {
2657
+ if (
2658
+ event.key === "Escape" &&
2659
+ !event.defaultPrevented &&
2660
+ !store.state.sheet &&
2661
+ !store.state.launcher
2662
+ ) {
2663
+ event.preventDefault();
2664
+ close();
2665
+ }
2666
+ };
2667
+
2668
+ addEventListener("keydown", onKey);
2669
+
2670
+ return () => removeEventListener("keydown", onKey);
2671
+ }, [open, leaving]);
2672
+
2673
+ if (!open) {
2674
+ return null;
2675
+ }
2676
+
2677
+ return html`<div class=${leaving ? "leaving" : ""} inert=${leaving}>
2678
+ <div
2679
+ class="overlay drawer-overlay"
2680
+ data-part="scrim"
2681
+ data-for="drawer"
2682
+ onMouseDown=${scrimPress(close)}
2683
+ >
2684
+ <aside
2685
+ class="drawer"
2686
+ data-part="drawer"
2687
+ data-state=${leaving ? "closing" : undefined}
2688
+ ref=${ref}
2689
+ >
2690
+ <${RailNav} />
2691
+ <${SessionList} compact=${true} />
2692
+ </aside>
2693
+ </div>
2694
+ </div>`;
2695
+ }