pi-pocket 0.27.0 → 0.28.0-beta.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 (93) hide show
  1. package/README.md +11 -8
  2. package/docs/architecture.md +9 -1
  3. package/docs/customizing.md +16 -2
  4. package/docs/docker.md +2 -0
  5. package/docs/examples/quiet-note.js +21 -0
  6. package/docs/examples/quiet-note.ts +73 -0
  7. package/docs/extensions/app.md +1 -0
  8. package/docs/extensions/policies/api-stability.md +3 -0
  9. package/docs/extensions/reference/limits.md +11 -0
  10. package/docs/extensions/reference/pocket.md +22 -1
  11. package/docs/extensions/reference/theme-surface.md +12 -0
  12. package/docs/extensions/reference/web.md +36 -2
  13. package/docs/extensions.md +2 -0
  14. package/docs/features.md +20 -16
  15. package/docs/map.md +24 -12
  16. package/docs/systemd.md +1 -1
  17. package/npm-shrinkwrap.json +3163 -0
  18. package/package.json +3 -2
  19. package/src/launcher/access.ts +75 -4
  20. package/src/launcher/main.ts +303 -60
  21. package/src/launcher/options.ts +8 -5
  22. package/src/launcher/serve.ts +677 -0
  23. package/src/server/app.ts +223 -14
  24. package/src/server/avatars.ts +54 -0
  25. package/src/server/background.ts +214 -42
  26. package/src/server/build.ts +53 -0
  27. package/src/server/commands.ts +28 -33
  28. package/src/server/config.ts +9 -1
  29. package/src/server/docs.ts +8 -1
  30. package/src/server/entry-presentation.ts +275 -0
  31. package/src/server/export.ts +26 -3
  32. package/src/server/extension-web.ts +113 -8
  33. package/src/server/extensions/pip.ts +57 -2
  34. package/src/server/host.ts +21 -3
  35. package/src/server/http/api.ts +106 -6
  36. package/src/server/http/assets.ts +9 -1
  37. package/src/server/http/conversation-routes.ts +61 -0
  38. package/src/server/http/events.ts +19 -0
  39. package/src/server/http/icon-route.ts +196 -0
  40. package/src/server/http.ts +41 -2
  41. package/src/server/icon-mask.ts +33 -0
  42. package/src/server/icon-render.ts +149 -0
  43. package/src/server/icon-store.ts +57 -0
  44. package/src/server/model-images.ts +124 -0
  45. package/src/server/pip.ts +30 -6
  46. package/src/server/projection.ts +127 -32
  47. package/src/server/room.ts +171 -8
  48. package/src/server/running.ts +307 -2
  49. package/src/server/schedules.ts +5 -0
  50. package/src/server/skills.ts +99 -8
  51. package/src/server/spend.ts +5 -0
  52. package/src/server/transcripts.ts +28 -3
  53. package/src/server/when.ts +25 -11
  54. package/types/pocket.d.ts +53 -2
  55. package/web/app-icon.js +149 -0
  56. package/web/app.js +12 -8
  57. package/web/avatar.js +46 -2
  58. package/web/composer.js +107 -15
  59. package/web/entry-presentation.js +264 -0
  60. package/web/extension-ui.js +18 -0
  61. package/web/fingerprint.d.ts +2 -0
  62. package/web/fingerprint.js +21 -0
  63. package/web/launcher.js +15 -3
  64. package/web/model-favorites.js +27 -0
  65. package/web/peeks.js +11 -3
  66. package/web/pip.js +7 -1
  67. package/web/running-board.js +1197 -0
  68. package/web/session-cache.js +144 -0
  69. package/web/session-tabs.js +58 -0
  70. package/web/sessions.js +51 -12
  71. package/web/sheets/all-artifacts.js +104 -0
  72. package/web/sheets/appearance.js +45 -0
  73. package/web/sheets/background.js +228 -0
  74. package/web/sheets/find.js +61 -7
  75. package/web/sheets/folder.js +43 -4
  76. package/web/sheets/menu.js +3 -1
  77. package/web/sheets/message.js +80 -15
  78. package/web/sheets/model.js +39 -3
  79. package/web/sheets/people.js +35 -1
  80. package/web/sheets/providers.js +80 -26
  81. package/web/sheets/schedules.js +4 -1
  82. package/web/sheets/shortcuts.js +1 -0
  83. package/web/sheets/text.js +2 -0
  84. package/web/sheets.js +11 -4
  85. package/web/store.js +837 -27
  86. package/web/style.css +1928 -166
  87. package/web/subagents-board.js +3 -2
  88. package/web/tab-order.js +34 -0
  89. package/web/theme-surface.js +7 -0
  90. package/web/theme.js +15 -0
  91. package/web/transcript.js +588 -57
  92. package/web/user-search.js +6 -0
  93. package/web/sheets/running.js +0 -130
package/src/server/app.ts CHANGED
@@ -51,12 +51,14 @@ import type { BrowserState } from "./browser/page.ts";
51
51
  import { Collab, REACTIONS } from "./collab.ts";
52
52
  import { Commands } from "./commands.ts";
53
53
  import { LinkedSessions } from "./linked-sessions.ts";
54
+ import { removeAvatar, saveAvatar } from "./avatars.ts";
54
55
  import { APP_ROOT, ConfigStore, modulesWith, type User } from "./config.ts";
55
56
  import {
56
57
  ArtifactAssetDoc,
57
58
  ArtifactBodyDoc,
58
59
  type ArtifactMeta,
59
60
  ArtifactsDoc,
61
+ type ArtifactType,
60
62
  AuthorsDoc,
61
63
  BackgroundDoc,
62
64
  type BackgroundTask,
@@ -93,6 +95,7 @@ import { Memory } from "./memory.ts";
93
95
  import { isThinkingLevel, modelInfo, modelList, resolveModel, THINKING_LEVELS } from "./models.ts";
94
96
  import { Updates } from "./updates.ts";
95
97
  import { pocketPackage, pocketVersion } from "./versions.ts";
98
+ import { serverBuild } from "./build.ts";
96
99
  import { compactionReader } from "./compaction.ts";
97
100
  import { configureHttp } from "./net.ts";
98
101
  import { createPublicFetch } from "./public-fetch.ts";
@@ -201,6 +204,26 @@ type SubagentsValue = {
201
204
 
202
205
  type SubagentsOf = { agents: Record<string, SubagentRecord>; reporting: Set<string> };
203
206
 
207
+ /** How many sessions the artifacts overview reads at once. */
208
+ const OVERVIEW_BATCH = 8;
209
+
210
+ /** One artifact in the artifacts overview: where it is, and which of its versions is the current one. */
211
+ export type ArtifactOverviewEntry = {
212
+ session: number;
213
+ sessionTitle: string;
214
+ id: string;
215
+ title: string;
216
+ type: ArtifactType;
217
+ kind?: "page" | "deck";
218
+ group?: string;
219
+ /** The number of the latest version: the one a person sees first. */
220
+ current: number;
221
+ /** How many versions there are. */
222
+ versions: number;
223
+ size: number;
224
+ updatedAt: number;
225
+ };
226
+
204
227
  /** One subagent on the subagents board: the subagents bar's view, the session it works in, and the call it waits on. */
205
228
  export type SubagentEntry = ReturnType<typeof subagentView> & {
206
229
  id: number;
@@ -322,6 +345,11 @@ export class PocketApp {
322
345
  readonly defaultCwd: string;
323
346
  readonly supervised: boolean;
324
347
  readonly startedAt = Date.now();
348
+ /**
349
+ * This server's code (`serverBuild`): sessions a tab keeps, in its memory or on the device, are good for a server of
350
+ * the same build, so they last across a restart but not across new code.
351
+ */
352
+ readonly build = serverBuild();
325
353
  /** Set by the launcher over IPC; undefined when the server runs on its own. */
326
354
  access: AccessInfo | undefined;
327
355
  harness!: Harness;
@@ -568,6 +596,14 @@ export class PocketApp {
568
596
  },
569
597
  // Everyone's tabs hear the new list in `hello`: commands are for guests too, not by a browser module's access.
570
598
  commandsChanged: () => this.#websChanged("all"),
599
+ presentationsChanged: () => {
600
+ for (const pending of this.#rooms.values()) {
601
+ void pending.then(
602
+ (room) => room.reproject(),
603
+ () => {},
604
+ );
605
+ }
606
+ },
571
607
  log: (line) => this.#log(line),
572
608
  // Something about a module only the owner can mend: their tabs, as what it says can name the server's folders.
573
609
  warn: (message) => this.ownerNotice("warning", message),
@@ -1523,13 +1559,78 @@ export class PocketApp {
1523
1559
  this.#peopleChanged(client.user.id);
1524
1560
  }
1525
1561
 
1526
- if (client.conversationId === undefined) {
1562
+ await this.#enter(client);
1563
+ }
1564
+
1565
+ /**
1566
+ * Show a tab another session, or none (the list), on the connection it has (`connection`, the id its `hello`
1567
+ * carried): it leaves the room of the one it showed, and gets what the new one has as a new connection would, with
1568
+ * what it kept of it (`have`). No new connection means no hello, session list, or PiP state again, and nobody sees
1569
+ * this person leave and come back. `switched` goes first: every event of a session after it is the new one's. A switch
1570
+ * numbered `seq` below one already taken arrived late, and is dropped. False when no such connection is open (it
1571
+ * closed, or the server started again): the tab connects again instead.
1572
+ */
1573
+ switchTo(
1574
+ user: User,
1575
+ connection: string,
1576
+ id: ConversationId | undefined,
1577
+ have: Client["have"],
1578
+ seq: number,
1579
+ ): boolean {
1580
+ let found = false;
1581
+
1582
+ for (const client of this.#clients) {
1583
+ if (client.user.id !== user.id || client.connection !== connection) {
1584
+ continue;
1585
+ }
1586
+
1587
+ found = true;
1588
+
1589
+ if (seq <= (client.switchSeq ?? -Infinity)) {
1590
+ continue;
1591
+ }
1592
+
1593
+ client.switchSeq = seq;
1594
+ const previous = client.conversationId;
1595
+
1596
+ if (previous !== undefined) {
1597
+ this.#leaveRoom(client, previous);
1598
+ }
1599
+
1600
+ client.conversationId = id;
1601
+
1602
+ if (have === undefined) {
1603
+ delete client.have;
1604
+ } else {
1605
+ client.have = have;
1606
+ }
1607
+
1608
+ client.send("switched", { seq, conversationId: id ?? null });
1609
+ void this.#enter(client);
1610
+
1611
+ if (id === undefined) {
1612
+ this.#scheduleSessions();
1613
+ }
1614
+ }
1615
+
1616
+ return found;
1617
+ }
1618
+
1619
+ /**
1620
+ * Put a tab in the room of the session it shows (`client.conversationId`), and send it what that session has: its
1621
+ * view, chat, notes, and browser. A later switch while the room opens wins: this one then leaves nothing behind.
1622
+ */
1623
+ async #enter(client: Client): Promise<void> {
1624
+ const visit = (client.visit = (client.visit ?? 0) + 1);
1625
+ const id = client.conversationId;
1626
+
1627
+ if (id === undefined) {
1527
1628
  return;
1528
1629
  }
1529
1630
 
1530
- if (!this.canSee(client.user, client.conversationId)) {
1631
+ if (!this.canSee(client.user, id)) {
1531
1632
  client.send("missing", {
1532
- conversationId: client.conversationId,
1633
+ conversationId: id,
1533
1634
  message: "This session is not shared with you.",
1534
1635
  });
1535
1636
  // Keep the tab for app-wide events only: nothing about that conversation reaches it, and it is not "there".
@@ -1539,11 +1640,23 @@ export class PocketApp {
1539
1640
  }
1540
1641
 
1541
1642
  try {
1542
- const id = client.conversationId;
1543
1643
  const room = await this.room(id);
1544
1644
 
1545
- if (!this.#clients.has(client)) {
1645
+ if (!this.#clients.has(client) || client.visit !== visit) {
1646
+ this.releaseRoom(room);
1647
+
1648
+ return;
1649
+ }
1650
+
1651
+ // The person's access can change while the room opens (`setAccess` evicts only tabs already there): asked
1652
+ // again now, as nothing of the session has gone yet.
1653
+ if (!this.canSee(client.user, id)) {
1546
1654
  this.releaseRoom(room);
1655
+ client.conversationId = undefined;
1656
+ client.send("missing", {
1657
+ conversationId: id,
1658
+ message: "This session is no longer shared with you.",
1659
+ });
1547
1660
 
1548
1661
  return;
1549
1662
  }
@@ -1568,10 +1681,9 @@ export class PocketApp {
1568
1681
  room.pushPresence();
1569
1682
  this.#scheduleSessions();
1570
1683
  } catch (error) {
1571
- client.send("missing", {
1572
- conversationId: client.conversationId,
1573
- message: describe(error),
1574
- });
1684
+ if (client.visit === visit) {
1685
+ client.send("missing", { conversationId: id, message: describe(error) });
1686
+ }
1575
1687
  }
1576
1688
  }
1577
1689
 
@@ -1866,6 +1978,26 @@ export class PocketApp {
1866
1978
  }
1867
1979
  }
1868
1980
 
1981
+ /** Set (bytes) or clear (undefined) someone's picture; everyone's lists show it at once. */
1982
+ setAvatar(user: User, bytes: Buffer | undefined): void {
1983
+ if (bytes === undefined) {
1984
+ removeAvatar(this.dataDir, user.id);
1985
+ this.config.updateUser(user.id, { avatar: undefined });
1986
+ } else {
1987
+ saveAvatar(this.dataDir, user.id, bytes);
1988
+ this.config.updateUser(user.id, { avatar: Date.now() });
1989
+ }
1990
+
1991
+ this.#peopleChanged();
1992
+
1993
+ for (const pending of this.#rooms.values()) {
1994
+ void pending.then(
1995
+ (room) => room.has(user.id) && room.pushPresence(),
1996
+ () => {},
1997
+ );
1998
+ }
1999
+ }
2000
+
1869
2001
  /** Someone came, went, or changed: remember when they were last here and tell everyone. */
1870
2002
  #peopleChanged(userId?: string): void {
1871
2003
  if (userId !== undefined && this.config.userById(userId) !== undefined) {
@@ -1900,6 +2032,7 @@ export class PocketApp {
1900
2032
  id: each.id,
1901
2033
  name: each.name,
1902
2034
  role: each.role,
2035
+ ...(each.avatar === undefined ? {} : { avatar: each.avatar }),
1903
2036
  online: this.#online(each.id),
1904
2037
  ...(each.lastSeen === undefined ? {} : { lastSeen: each.lastSeen }),
1905
2038
  ...(each.sessions === undefined || scope !== undefined
@@ -2256,6 +2389,14 @@ export class PocketApp {
2256
2389
  refreshModels: user.role === "owner",
2257
2390
  // Tells the web app this server sends peek tiles (`POST /api/peeks`, `peek` events).
2258
2391
  peeks: true,
2392
+ // Tells the web app it may show another session on the connection it has (`POST /api/switch`).
2393
+ switches: true,
2394
+ // Sessions tabs keep are good for servers of this build (`have`).
2395
+ build: this.build,
2396
+ // Whether a browser may keep sessions on the device (IndexedDB), for every tab and across reloads:
2397
+ // `PI_POCKET_SESSION_CACHE=off` keeps them in each tab's memory only, and has browsers drop what they
2398
+ // kept on the device.
2399
+ deviceCache: process.env.PI_POCKET_SESSION_CACHE !== "off",
2259
2400
  // This server's clock: peek tiles compare the browser's looks with when runs ended here.
2260
2401
  now: Date.now(),
2261
2402
  // Collaboration features: 2 adds roles, take turns, reactions, pins, notes, mentions, and push.
@@ -2508,7 +2649,9 @@ export class PocketApp {
2508
2649
  const agent = (room.value?.docs["pi.agent"] ?? {}) as AgentState;
2509
2650
  const forkedFrom = meta?.forkedFrom;
2510
2651
  const root = this.rootOf(room.id);
2511
- const budget = this.#sessions[String(root)]?.budget;
2652
+ const subagent = meta === undefined && room.parent !== undefined;
2653
+ // A subagent shows what it cost itself: the session's spend and limit are on the session.
2654
+ const budget = subagent ? undefined : this.#sessions[String(root)]?.budget;
2512
2655
 
2513
2656
  return {
2514
2657
  id: room.id,
@@ -2532,10 +2675,11 @@ export class PocketApp {
2532
2675
  ...(forkedFrom === undefined ? {} : { forkedFrom }),
2533
2676
  // The session's spend with its subagents', and its limit, with what counts against it.
2534
2677
  spend: {
2535
- spent:
2536
- budget === undefined
2537
- ? this.spend.sessionSpent(root)
2538
- : this.spend.budgetSpent(root),
2678
+ spent: subagent
2679
+ ? this.spend.conversationSpent(room.id)
2680
+ : budget === undefined
2681
+ ? this.spend.sessionSpent(root)
2682
+ : this.spend.budgetSpent(root),
2539
2683
  ...(budget === undefined ? {} : { budget }),
2540
2684
  },
2541
2685
  ...(meta?.worktree === undefined
@@ -2769,6 +2913,7 @@ export class PocketApp {
2769
2913
 
2770
2914
  #forget(userId: string): void {
2771
2915
  this.config.removeUser(userId);
2916
+ removeAvatar(this.dataDir, userId);
2772
2917
  this.pushStore?.removeUser(userId);
2773
2918
 
2774
2919
  // Their open tabs end now; reconnecting fails, so they land on the sign-in screen.
@@ -2822,6 +2967,70 @@ export class PocketApp {
2822
2967
  }
2823
2968
  }
2824
2969
 
2970
+ /**
2971
+ * Every artifact in the sessions this person can see, for the artifacts overview: one entry for each, with its
2972
+ * current (latest) version and how many versions it has. Archived sessions are left out. Newest first.
2973
+ */
2974
+ async artifactOverview(user: User): Promise<ArtifactOverviewEntry[]> {
2975
+ const one = async (
2976
+ session: string,
2977
+ meta: SessionMeta,
2978
+ ): Promise<ArtifactOverviewEntry[]> => {
2979
+ const id = Number(session) as unknown as ConversationId;
2980
+
2981
+ // A PiP is its owner's assistant, and kept out of the session list.
2982
+ if (meta.archived === true || meta.pip !== undefined || !this.canSee(user, id)) {
2983
+ return [];
2984
+ }
2985
+
2986
+ try {
2987
+ const index = await this.harness.snapshot(ArtifactsDoc, id, context);
2988
+ const entries: ArtifactOverviewEntry[] = [];
2989
+
2990
+ for (const [artifact, item] of Object.entries(index?.items ?? {})) {
2991
+ const current = item.versions.at(-1);
2992
+
2993
+ if (current === undefined) {
2994
+ continue;
2995
+ }
2996
+
2997
+ entries.push({
2998
+ session: Number(session),
2999
+ sessionTitle: meta.title ?? "",
3000
+ id: artifact,
3001
+ title: item.title,
3002
+ type: item.type,
3003
+ ...(item.kind === undefined ? {} : { kind: item.kind }),
3004
+ ...(item.group === undefined ? {} : { group: item.group }),
3005
+ current: current.version,
3006
+ versions: item.versions.length,
3007
+ size: current.size,
3008
+ updatedAt: current.createdAt,
3009
+ });
3010
+ }
3011
+
3012
+ return entries;
3013
+ } catch (error) {
3014
+ // One session's broken artifacts must not hide the others'.
3015
+ console.error(`Artifacts of session ${session} could not be read:`, error);
3016
+
3017
+ return [];
3018
+ }
3019
+ };
3020
+
3021
+ const sessions = Object.entries(this.#sessions);
3022
+ const found: ArtifactOverviewEntry[] = [];
3023
+
3024
+ // A few sessions at a time: a person with many sessions does not make the server read all of them at once.
3025
+ for (let from = 0; from < sessions.length; from += OVERVIEW_BATCH) {
3026
+ const batch = sessions.slice(from, from + OVERVIEW_BATCH);
3027
+
3028
+ found.push(...(await Promise.all(batch.map(([id, meta]) => one(id, meta)))).flat());
3029
+ }
3030
+
3031
+ return found.sort((a, b) => b.updatedAt - a.updatedAt);
3032
+ }
3033
+
2825
3034
  async artifactBody(id: ConversationId, artifact: string, version?: number) {
2826
3035
  const index = await this.harness.snapshot(ArtifactsDoc, id, context);
2827
3036
  // Its own entries only: `__proto__` and the like name no artifact.
@@ -0,0 +1,54 @@
1
+ /**
2
+ * People's profile pictures, kept as files in the data folder (`avatars/<person id>`). The person's record holds only a
3
+ * version (when the picture was set), which is in the picture's address so a browser never shows a stale one.
4
+ */
5
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { HttpError } from "./errors.ts";
8
+ import { sniffImage } from "./http/assets.ts";
9
+
10
+ /** The most a stored picture can be. The web app shrinks pictures to a few KB before it sends them. */
11
+ export const MAX_AVATAR = 512 * 1024;
12
+
13
+ /** Types the picture may have: not SVG (script), not formats some browsers cannot draw. */
14
+ const TYPES = new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]);
15
+
16
+ const folder = (dataDir: string) => join(dataDir, "avatars");
17
+ // Person ids are made by the server (`config.ts`); the check keeps a bad id from leaving the folder.
18
+ const fileOf = (dataDir: string, userId: string) =>
19
+ join(folder(dataDir), userId.replace(/[^\w-]/g, "_"));
20
+
21
+ /** Keep a picture for a person; throws HttpError when it is not an image of an allowed type. */
22
+ export function saveAvatar(dataDir: string, userId: string, bytes: Buffer): void {
23
+ if (bytes.length === 0) {
24
+ throw new HttpError(400, "No picture was sent");
25
+ }
26
+
27
+ const type = sniffImage(bytes.subarray(0, 1024));
28
+
29
+ if (type === undefined || !TYPES.has(type)) {
30
+ throw new HttpError(415, "A picture is a PNG, JPEG, WebP, or GIF image");
31
+ }
32
+
33
+ mkdirSync(folder(dataDir), { recursive: true });
34
+ writeFileSync(fileOf(dataDir, userId), bytes, { mode: 0o600 });
35
+ }
36
+
37
+ /** The picture and its type, or undefined when the person has none. */
38
+ export function readAvatar(
39
+ dataDir: string,
40
+ userId: string,
41
+ ): { bytes: Buffer; type: string } | undefined {
42
+ if (!existsSync(fileOf(dataDir, userId))) {
43
+ return undefined;
44
+ }
45
+
46
+ const bytes = readFileSync(fileOf(dataDir, userId));
47
+ const type = sniffImage(bytes.subarray(0, 1024));
48
+
49
+ return type === undefined ? undefined : { bytes, type };
50
+ }
51
+
52
+ export function removeAvatar(dataDir: string, userId: string): void {
53
+ rmSync(fileOf(dataDir, userId), { force: true });
54
+ }